<?php
/**
 * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

/**
 * 采购员/仓库管理员  盘点功能  货架管理【上下架商品】
 * User: poptser
 * Email: poptser@foxmail.com
 * Date: 2016/10/31
 * Time: 17:45
 */

namespace SDXApi\Controller;
use Think\Controller;
use Think\Model;
use Common\Api\Ali_ossApi;

class PurchaseController extends AppController
{
    public $wprow;
    public $pagesize=10;
    public $img_site='https://image.shidexian.com/';
    public function _initialize($apptoken = '', $apptime = '', $check_uid = false, $session_id = '', $check_sign = true, $set_action = true)
    {
        parent::_initialize($apptoken, $apptime, $check_uid, $session_id, false);

        $warehouse_personnel=M('warehouse_personnel');
        $user_id=I('request.user_id','intval');
        $this->wprow=$warehouse_personnel->field('position,wid,uid,longitude,latitude,status')->where(array('uid'=>$user_id,'position'=>3,'status'=>1))->find();
        //dump($warehouse_personnel->getLastSql());
        if(!$this->wprow&&!strpos(__ACTION__,"load_log")){

            returnApiError("无此操作权限");
        }
    }

    /**
     * todo 根据用户ID获取仓库ID
     * rui poptser@foxmail.com 2016-10-10 10:09:19
     * @param $user_id
     */
    private function get_user_wid_identity($user_id){
        //$user_wid = S("swid_".$user_id);
        if(empty($user_wid)){
            $user_wid = M("warehouse_personnel")->where(array("uid"=>$user_id))->getField("wid");
            //S("swid_".$user_id,$user_wid);
        }
        return $user_wid;
    }

    /**
     * 获取商品调仓冻库
     * Author:poptser@foxmail.com
     * @param $goods_id
     * @param $wid
     * @return mixed
     */
    public function get_good_zc_dy_dc($goods_id, $wid){
        //查询日常调仓状态未变为"货品到达"-来源仓商品
        $out_the_warehouse_goodswhere='twr.the_warehousecause=1 AND twr.the_warehouse_status =1';
        $out_the_warehouse_goodswhere.=' AND twr.callout_wid='.$wid.' AND twgr.goods_id='.$goods_id;

        $out_the_warehouse_goods=M('the_warehouse_record')->alias('twr')
            ->join(C ( 'DB_PREFIX' ) .'the_warehouse_goods_record as twgr ON twr.id=twgr.twid')
            ->where($out_the_warehouse_goodswhere)
            ->getField("twgr.the_warehouse_num");

        return $out_the_warehouse_goods;
    }
    /**
     * 获取商品调仓冻库
     * Author:poptser@foxmail.com
     * @param $goods_id
     * @param $wid
     * @return mixed
     */
    public function get_good_cc_dy_dc($goods_id, $wid){
        //查询日常调仓状态为"货品到达"-目标仓商品
        $in_the_warehouse_goodswhere='twr.the_warehousecause=1 AND twr.the_warehouse_status in(2,3)';
        $in_the_warehouse_goodswhere.=' AND twr.callin_wid='.$wid.' AND twgr.goods_id='.$goods_id;

        $in_the_warehouse_goods=M('the_warehouse_record')->alias('twr')
            ->join(C ( 'DB_PREFIX' ) .'the_warehouse_goods_record as twgr ON twr.id=twgr.twid')
            ->where($in_the_warehouse_goodswhere)
            ->getField("twgr.the_warehouse_num");
        return $in_the_warehouse_goods;
    }
    /**
     * 在仓冻余
     * @param $goods_id
     * @param $wid
     * @return int
     */
    public function get_good_zz_dy($goods_id,$wid){
        //查询出仓冻余
        //查询 已出仓&未确认收货&未取消的订单的商品数

        $where['oi.order_status']=array("neq",2);       //未取消
        $where['oi.shipping_status']=array("neq",2);    //未确认收货
        $where['oi.pay_status']=array("gt",1);          //已支付
        $where['oi.outgo'] = 0;                           //已出仓
        //$where['oi.shipping_id'] = 3;                   //配送单
        $where['oi.196_admin_id'] = 0;                  //非异常单
        $where['oi.wid'] = $wid;
        $where['og.goods_id']=$goods_id;        //当前商品ID
        $where['_string']="og.order_id = oi.order_id";        //当前商品ID

        $order_goods = M('')->table(
            array(
                "sdx_order_info"=>"oi",
                "sdx_order_goods"=>"og",
            )
        )->where($where)->field("og.*")->select();

        //dump(M('')->getLastSql());
        $out_dj_num = 0;
        foreach ($order_goods as $key=>$vaule){
            $refund_detail = M("refund_detail")->
            field("sum(refund_number) as refund_number ,sum(surplus_number) as surplus_number")
                ->where(array("order_goods_id"=>$vaule['rec_id']))->find();
            if($refund_detail['refund_number']>0){
                $out_dj_num = $out_dj_num+$refund_detail['surplus_number'];
            }else{
                $out_dj_num = $out_dj_num+$vaule['goods_number'];   //冻结库存出仓
            }
        }
        return $out_dj_num;
    }
    /**
     * 出仓冻余
     * @param $goods_id
     * @param $wid
     * @return int
     */
    public function get_good_cc_dy($goods_id,$wid){
        //查询出仓冻余
        //查询 已出仓&未确认收货&未取消的订单的商品数

        $where['oi.order_status']=array("neq",2);       //未取消
        $where['oi.shipping_status']=array("neq",2);    //未确认收货
        $where['oi.pay_status']=array("gt",1);          //已支付
        $where['oi.outgo'] = array("neq",0);                           //已出仓
        $where['og.goods_id']=$goods_id;        //当前商品ID
        //$where['oi.shipping_id'] = 3;                   //配送单
        $where['oi.196_admin_id'] = 0;                  //非异常单
        $where['oi.wid'] = $wid;
        $where['_string']="og.order_id = oi.order_id";        //当前商品ID

        $order_goods = M('')->table(
            array(
                "sdx_order_info"=>"oi",
                "sdx_order_goods"=>"og",
            )
        )->where($where)->field("og.*")->select();

        //dump(M('')->getLastSql());
        $out_dj_num = 0;
        foreach ($order_goods as $key=>$vaule){
            $refund_detail = M("refund_detail")->
            field("sum(refund_number) as refund_number ,sum(surplus_number) as surplus_number")
                ->where(array("order_goods_id"=>$vaule['rec_id']))->find();
            if($refund_detail['refund_number']>0){
                $out_dj_num = $out_dj_num+$refund_detail['surplus_number'];
            }else{
                $out_dj_num = $out_dj_num+$vaule['goods_number'];   //冻结库存出仓
            }
        }
        return $out_dj_num;
    }
    /**
     * TODO 扫描二维码或者输入商品货号 返回 仓库信息  scan_good
     * poptser@foxmail.com
     * 2016-10-31 17:52:05
     */
    public function scanner_goods(){
        $wp_userid=I('post.user_id','intval');
        $goods_sn=I('post.goods_number');    //扫描或者手动输入商品货号

        if(empty($wp_userid)){
            returnApiError('UID 为空');
        }
        if (empty($goods_sn)){
            returnApiError("商品ID/商品货号未找到");
        }
        $is_goods = M("goods")->where(array("goods_sn"=>$goods_sn))->find();
//        dump(M("goods")->getLastSql());
//        dump($is_goods);
        if(!$is_goods){
            returnApiError("无此商品".$_POST['goods_num']);
        }
        if($is_goods['is_delete']!=0){
            returnApiError("商品已删除");
        }
        $wid = $this->get_user_wid_identity($wp_userid);


        $wheres="gs.wid=".$wid." and g.goods_sn = '".$goods_sn."' and gs.goods_id=g.goods_id and g.is_delete =0";
        $list=M('')->table('sdx_goods_storage as gs,sdx_goods as g')
            ->field('gs.goods_id,g.goods_name,g.shop_price,g.goods_sn,gs.wid,gs.practical_num,gs.freeze_num,gs.inferior_quality_num,(gs.practical_num+gs.freeze_num) as in_warehouse_num')
            ->where($wheres)->find();
        if($list){




            $out_dj_num = $this->get_good_cc_dy($list['goods_id'],$wid); //冻结出仓
            $in_dj_num = $this->get_good_zz_dy($list['goods_id'],$wid);  //冻结在仓
            $in_dc_num = $this->get_good_zz_dy_dc($list['goods_id'],$wid);  //调仓冻库
            $out_dc_num = $this->get_good_cc_dy_dc($list['goods_id'],$wid);  //调仓冻库
            $new_all = $list['practical_num'] + $out_dj_num+$in_dj_num+$in_dc_num+$out_dc_num;//实际剩余库存+冻结库存

//            if ($list['goods_id']==15785&&$_POST['user_id']==190){
//                dump($in_dj_num);
//                exit();
//            }
            $re_data['practical_num'] =
                "总库存：".$new_all.
                "\n库存 [ 实:".$list['practical_num']." + 订单冻在:".$in_dj_num." + 调仓冻在:".$in_dc_num." ]\n
                订单冻出：" .$out_dj_num." 调仓冻出：".$out_dc_num;


            $list['source_warehouse']=$list['wid'];
            $wlist=$this->get_warehousename($list['wid']);
            $list['source_warehouse_name']=$wlist['name'];

            $re_data['id'] = $list['goods_id'];
            $re_data['name'] = $list['goods_name'];
            $re_data['goods_number'] = $list['goods_sn'];
//            $re_data['practical_num'] = $list['practical_num'];     //实际库存数
//            $re_data['inferior_quality_num'] = $list['inferior_quality_num'];   //次品库存数
//            $re_data['freeze_num'] = $list['freeze_num'];       //冻结库存数
            $re_data['price'] = $list['shop_price'];       //本店售价
            $re_data['vip_price'] = $this->get_vip_price($list['goods_id'],$list['shop_price']);       //本店售价

            //dump($goods_sn);

            //$goods_sn=$list['goods_sn'];             //商品货号
            $model = M();
            $sql = "SELECT sh.*,sc.name AS shelf_tag,sl.name AS shelf_type,wh.name AS shelf_store,sg.sh_floor AS putaway_row,
                sh.shelves_sn AS shelf_num
                FROM sdx_shelves AS sh,sdx_shelves_cat AS sc,sdx_shelves_class AS sl ,sdx_warehouse AS wh,sdx_shelves_goods AS sg
                WHERE 
                sh.category_id = sc.id AND sh.class_id = sl.id AND sh.wid =  wh.id AND sg.sh_id = sh.id AND sh.wid = '.$wid.' 
                AND sg.goods_sn = '".$goods_sn."'";
            $list_sh  = $model->query($sql);
            if($list_sh){
                $i=0;
                foreach ($list_sh as $value){
                    if($i==0){
                        $re_data['shelf_num'] .= $value['shelf_tag']."-".$value['shelf_type']."  编号：".$value['shelf_num']." 列：[ ".$value['putaway_row']." ]";
                    }else{
                        $re_data['shelf_num'] .= "\n".$value['shelf_tag']."-".$value['shelf_type']."  编号：".$value['shelf_num']." 列：[ ".$value['putaway_row']." ]";
                    }
                    $i++;
                }
            } else {
                $re_data['shelf_num'] = "无货架信息";       //货架编号
            }


            //根据目前所在货架。。生成缓存信息
            //dump($goods_sn);

            $my_sh_array = M("shelves")->where(array("state"=>1,"wid"=>$wid))->getField("id",true);

            $sh_where['goods_sn'] = $goods_sn;
            $sh_where['sh_id'] = array("in",$my_sh_array);
            $shelves_goods = M("shelves_goods")->where($sh_where)->select();
            if(!$shelves_goods){
                returnApiError("师弟莫慌\n这个商品没在货架上，要盘点先上架先");
            }
            //dump($shelves_goods);
            $re_cache = array();
            $new_number = 0;
            $re_data['can_submit'] = 1; //是否可以提交
            foreach ($shelves_goods as $key=>$value){
                $cache_data = M("take_stock_inventory_cache")
                    ->where(array("goods_id"=>$list['goods_id'],"type"=>0,"sh_id"=>$value['sh_id'],"line"=>$value['sh_floor'],"show"=>0))
                    ->order('ctime desc')
                    ->find();
                //dump($cache_data);
                $new_array = array();
                if($cache_data){
                    //存在缓存记录
                    //dump("存在");
                    $new_array['id'] = $cache_data['id'];
                    $new_array['shelf_num'] =M("shelves")->where(array("id"=>$cache_data['sh_id']))->getField("shelves_sn")."-".$cache_data['line'];
                    $new_array['check_count'] =$cache_data['now_number'];
                    $new_array['author_info'] =$cache_data['user']."\n".local_date('Y-m-d H:i:s', $cache_data['ctime']);
                    //dump($new_array);
                    //查询最近一次提交数
                    $last_cache_data = M("take_stock_inventory_cache")
                        ->where(array("goods_id"=>$list['goods_id'],"type"=>1,"sh_id"=>$value['sh_id'],"line"=>$value['sh_floor']))
                        ->order('ctime desc')
                        ->find();
                    if($last_cache_data){
                        $new_array['count_last_check'] =$last_cache_data['now_number']." [ ".local_date('Y-m-d H:i:s',$last_cache_data['ctime'])." ]";
                    }else{
                        $new_array['count_last_check'] ="N/A";
                    }
                    array_push($re_cache,$new_array);
                    $new_number +=$cache_data['now_number'];
                }else{
                    //不存在缓存记录，新加记录并返回
                    //dump("不存在");
                    $new_array['id'] = 0;
                    $new_array['shelf_num'] =M("shelves")->where(array("id"=>$value['sh_id']))->getField("shelves_sn")."-".$value['sh_floor'];
                    $new_array['check_count'] =0;
                    $new_array['author_info'] ="N/A";
                    //查询最近一次提交数
                    $last_cache_data = M("take_stock_inventory_cache")
                        ->where(array("goods_id"=>$list['goods_id'],"type"=>1,"sh_id"=>$value['sh_id'],"line"=>$value['sh_floor']))
                        ->order('ctime desc')
                        ->find();
                    if($last_cache_data){
                        $new_array['count_last_check'] =$last_cache_data['now_number']." [ ".local_date('Y-m-d H:i:s',$last_cache_data['ctime'])." ]";
                    }else{
                        $new_array['count_last_check'] ="N/A";
                    }
                    array_push($re_cache,$new_array);
                    $re_data['can_submit'] = 0; //是否可以提交
                }
            }



            //在仓库存 = 实余 + 在仓冻余
            //在仓冻余 = 在仓库存 - 实余
            //冻结库存 = 在仓冻余 + 出仓冻余
            //冻结库存 = （在仓库存 - 实余） + 出仓冻余
            //盘点数量 = 库存总数 = 在仓库存 + 出仓冻余
            //新实余 = 盘点数量 - 冻余
            //新实余 = （在仓库存 + 出仓冻余） - （在仓冻余 + 出仓冻余）
            //新实余 = 在仓库存 + 出仓冻余 - 在仓冻余 - 出仓冻余
            //新实余 = 在仓库存 - 在仓冻余



            $re_data['list_shelf_check'] = $re_cache;

            //$new_number 在仓库存
            if($new_number<$in_dj_num){
                $new_number = $in_dj_num;
            }

            $new_na = $new_number - $in_dj_num;
            $new_all = $new_number + $out_dj_num;

            $re_data['all_shelf_check_info'] =
                "总库存：".$new_all.
                "\n在仓库存 [ 实余：".$new_na." + 冻在:".$in_dj_num." ]\n冻出：" .$out_dj_num;



            $procurement_id = M("warehouse_procurement_detail")->where(array("goods_id"=>$re_data['id']))->order("id desc")->getField("procurement_id");
            $supplier_id  = M("warehouse_procurement")->where(array("id"=>$procurement_id))->getField("supplier_id");
            $re_data['provider'] = M("warehouse_supplier")->where(array("id"=>$supplier_id))->getField("name");
            returnApiSuccess($re_data,'已返回数据');

        }else{
            returnApiError("此商品未入库");
            //w_log("log2",M('')->getlastsql());
//            $is_storage = M("goods_storage")->where(array("wid"=>$wid,"goods_sn"=>$goods_sn))->count();
//            if($is_storage==0){
//                //未有采购库存记录，创建
//
//                $goods_data = M('goods')->where(array("goods_sn"=>$goods_sn))->find();
//
//                $data['wid'] =$wid ;
//                $data['goods_id'] = $goods_data['goods_id'];
//                $data['goods_sn'] = $goods_sn;
//                $data['goods_name'] = $goods_data['goods_name'];
//                $data['practical_num'] = 0;
//                $data['freeze_num'] = 0;
//                $data['inferior_quality_num'] = 0;
//                $data['add_time'] = gmtime();
//                $add_r = M("goods_storage")->add($data);
//                if($add_r){
//                    returnApiError("本商品未采购，自动生成采购记录\n请重新扫描执行盘点");
//                }else{
//                    returnApiError("本商品未采购，且自动生成采购失败");
//                }
//            }else{
//                returnApiError("本仓库未找到此商品");
//            }

        }

    }


    /**
     * TODO 暂存数据
     */
    public function set_shelf_check_count(){
        $user_id=I('post.user_id','');
        $check_count=I('post.check_count','');
        $shelf_num=I('post.shelf_num');
        $remark=I('post.remark');
        $good_id=I('post.good_id','');
        $shelf_date = explode("-",$shelf_num);
        if(!is_numeric($good_id)||!is_numeric($check_count)){
            returnApiError("数据异常");
        }
        if(count($shelf_date)>1){
            //是货架与列的组合
            $goods_data = M("goods")->where(array("goods_id"=>$good_id))->field("goods_sn,goods_name")->find();

            if(!$goods_data){
                returnApiError("未找到此商品");
            }
            $wid = $this->get_user_wid_identity($user_id);
            $sh_id = M("shelves")->where(array("shelves_sn"=>$shelf_date[0],"wid"=>$wid))->getField("id");

            $shelves_goods = M("shelves_goods")->
            where(array("goods_sn"=>$goods_data['goods_sn'],"sh_id"=>$sh_id,"sh_floor"=>$shelf_date[1]))->count();
            if($shelves_goods==0){
                returnApiError("商品未在此货架上".$goods_data['goods_sn']."-".$sh_id."-".$shelf_date[1]);
            }

            //清楚此货架其它缓存
            M("take_stock_inventory_cache")->
            where(array("sh_id"=>$sh_id,"line"=>$shelf_date[1],"type"=>0,"show"=>1))->setField("show",1);

            $data['sh_id'] = $sh_id;
            $data['line'] = $shelf_date[1];

            $data['now_number'] = $check_count;
            $data['ctime'] = gmtime();
            $data['remark'] = $remark;
            $data['goods_id'] = $good_id;
            $user_info = A("Distribution")->get_admin_user_name($user_id);
            $data['user'] = $user_info['user_name'];

            $data['goods_sn'] = $goods_data['goods_sn'];
            $data['goods_name'] = $goods_data['goods_name'];

            $r = M("take_stock_inventory_cache")->add($data);

            if($r){
                returnApiSuccess(null,"成功");
            }else{
                returnApiError("更新缓存失败");
            }
        }else{
            returnApiError("货架数据不包含列数");
        }
    }

    /**
     * TODO 根据缓存内容提交盘点
     */
    public function submit_check(){
        $user_id=I('post.user_id');    //用户ID
        $good_id=I('post.good_id');    //商品ID
        $remark=I('post.remark');               //备注
        if(empty($good_id)){
            returnApiError("商品ID为空");
        }else{
            //查询此商品的缓存记录--只查询缓存中，未上传的记录
            $goods_data = M("goods")->where(array("goods_id"=>$good_id))->field("goods_sn,goods_name")->find();

            $shelves_goods = M("shelves_goods")->
            where(array("goods_sn"=>$goods_data['goods_sn']))->select();
            $new_number = 0;
            $str = "";
            foreach ($shelves_goods as $key=>$value){
                $cache_data = M("take_stock_inventory_cache")->
                where(array("show"=>0,"goods_id"=>$good_id,"type"=>0,"sh_id"=>$value['sh_id'],"line"=>$value['sh_floor']))->order("ctime desc")->find();
                $new_number = $new_number + $cache_data['now_number'];
                if($key==0){
                    $str = $cache_data['id'];
                }else{
                    $str .= ",".$cache_data['id'];
                }
            }
//            dump($new_number);
//            exit();
            if($new_number>=0){


                $re = $this->set_check_count($user_id,$good_id,$new_number,$remark,0,$shelf=false);
                //returnApiError($new_number);
                if($re['state']){
                    $where['id']=array("in",$str);
                    $data['type'] = 1;
                    $user_info = A("Distribution")->get_admin_user_name($user_id);
                    $data['user'] = $user_info['user_name'];
                    $data['ctime'] = gmtime();
                    M("take_stock_inventory_cache")->where($where)->save($data);
                    M("take_stock_inventory_cache")->where(array("goods_id"=>$good_id))->setField('show',1);
                    //returnApiError($re['msg']);
                    returnApiSuccess(null,"成功");
                }else{
                    returnApiError($re['msg']);
                }
            }else{
                returnApiError("缓存数据已经被提交，请重新打开");
            }

        }
    }

    /**
     * 载入记录
     */
    public function load_log(){
        $user_id=I('post.user_id');    //用户ID
        $type=I('post.type');    //类型: 1实余,2冻余,3货架盘点
        $page=I('post.page');    //页码
        $goods_id=I('post.goods_id');    //商品id
        $shelf_num=I('post.shelf_num');    //货架编号
        //dump($goods_id);
        $wid = $this->get_user_wid_identity($user_id);
        if($type==3){
            $this->show_pd_cache($goods_id,$shelf_num,$wid);
        }else if($type==1){
            $this->show_pd_kc_log($goods_id,$wid);
        }else if($type==2){
            $this->show_pd_dy_log($goods_id,$wid);
        }else{
            returnApiError("错误操作");
        }



    }


    private function get_username($uid){
        $result = M('warehouse_personnel')->where('uid=' . $uid)->getField("name");
        return $result;
    }

    /*
 * 获取普通用户名称
 * */
    private function check_whether_average($user_id){
        $users=M('users')->where(array('user_id'=>$user_id))->getField("user_name");
        if($users){
            return $users;
        }else{
            return false;
        }
    }
    /**
     * TODO 冻结库存列表
     * @param $goods_id
     */
    public function show_pd_dy_log($goods_id,$wid){
        $where='gs.wid=w.id and gs.id=gfr.goods_storage_id  and gs.goods_id=g.goods_id and g.goods_id='.$goods_id.' and w.id ='.$wid;
        $list=M('')->table('sdx_goods_storage as gs,sdx_warehouse as w,sdx_goods_freeze_record as gfr,sdx_goods as g')
            ->field('gfr.id,g.goods_id,g.goods_name,g.goods_sn,gs.wid,gs.practical_num,gs.freeze_num,gfr.freeze_num as operation_num,gfr.operation_userid,gfr.operation_addtime,gfr.source_no,gfr.record_type,gfr.real_num,gfr.frozen_num,gfr.defective_num,gfr.remark')
            ->where($where)->limit(100)
            ->order('gfr.id desc,gfr.operation_addtime desc')
            ->select();
        if($list){
            $data['list'] = array();
            foreach ($list as $k=>$v){
                $record_type_name='';
                $operation='';
                if($v['record_type']==1){
                    $record_type_name='调仓入库';
                    $operation='-';
                }elseif ($v['record_type']==2){
                    $record_type_name='调仓出库';
                    $operation='+';
                }elseif ($v['record_type']==3){
                    $record_type_name='订单完成';
                    $operation='-';
                }elseif ($v['record_type']==4){
                    $record_type_name='商品下单';
                    $operation='+';
                }elseif ($v['record_type']==5){
                    $record_type_name='订单取消';
                    $operation='-';
                }elseif ($v['record_type']==6){
                    $record_type_name='确认收货';
                    $operation='-';
                }elseif ($v['record_type']==7){
                    $record_type_name='调仓入库';
                    $operation='+';
                }elseif ($v['record_type']==8){
                    $record_type_name='调仓出库';
                    $operation='-';
                }elseif ($v['record_type']==9){
                    $record_type_name='缺货退款';
                    $operation='-';
                }elseif ($v['record_type']==10){
                    $record_type_name='商品取消';
                    $operation='-';
                }elseif ($v['record_type']==11){
                    $record_type_name='次品退款';
                    $operation='-';
                }elseif ($v['record_type']==12){
                    $record_type_name='退货退款';
                    $operation='-';
                }elseif ($v['record_type']==13){
                    $record_type_name='系统盘点';
                    $operation='+';
                }elseif ($v['record_type']==14){
                    $record_type_name='在仓回流';
                    $operation='-';
                }elseif ($v['record_type']==15){
                    $record_type_name='调仓取消';
                    $operation='-';
                }elseif ($v['record_type']==16){
                    $record_type_name='系统重置';
                    $operation='-';
                }
                $list[$k]['record_type_name']=$record_type_name;
                $list[$k]['operation']=$operation;
                $operation_username=$this->get_username($v['operation_userid']);
                if($operation_username){
                    $list[$k]['operation_username']=$operation_username;
                }else{
                    $operation_username=$this->check_whether_average($v['average_userid']);
                    $list[$k]['operation_username']=$operation_username;
                }
                $list[$k]['operation_addtime']=local_date('Y-m-d H:i:s',$v['operation_addtime']);
                $str = "商品名称：".$list[$k]['goods_name']
                    ."\n类型数量：" .$list[$k]['record_type_name']." [ ".$list[$k]['operation'].$list[$k]['operation_num']." ] "
                    ."\n剩余数量：".$list[$k]['frozen_num']
                    ."\n    操作者：".$list[$k]['operation_username']." [ ".$list[$k]['operation_addtime']." ] ";
                array_push($data['list'],$str);
            }
            $data['is_last'] =1 ;
            returnApiSuccess($data,"已返回");
        }else{
            returnApiError("无记录");
        }
    }


    /**
     * TODO 实际库存列表
     * @param $goods_id
     */
    public function show_pd_kc_log($goods_id,$wid){
        $where='gs.wid=w.id and gs.id=gsr.goods_storage_id  and gs.goods_id=g.goods_id and g.goods_id='.$goods_id.' and w.id ='.$wid;
        $list=M()->table('sdx_goods_storage as gs,sdx_warehouse as w,sdx_goods_storage_record as gsr,sdx_goods as g')
            ->field('gsr.id,g.goods_id,g.goods_name,g.goods_sn,gs.wid,gs.practical_num,gs.freeze_num,gsr.operation_num,gsr.operation_userid,gsr.average_userid,gsr.operation_addtime,gsr.source_no,gsr.record_type,gsr.real_num,gsr.frozen_num,gsr.defective_num')
            ->where($where)->limit(100)
            ->order('gsr.id desc,gsr.operation_addtime desc')
            ->select();
        if($list){
            $data['list'] = array();
            foreach ($list as $k=>$v){
                $record_type_name='';
                $operation='';
                if($v['record_type']==1){
                    $record_type_name='采购入库';
                    $operation='+';
                }elseif ($v['record_type']==2){
                    $record_type_name='调仓入库';
                    $operation='+';
                }elseif ($v['record_type']==3){
                    $record_type_name='调仓出库';
                    $operation='-';
                }elseif ($v['record_type']==4){
                    $record_type_name='配送出库';
                    $operation='-';
                }elseif ($v['record_type']==5){
                    $record_type_name='次品录入';
                    $operation='-';
                }elseif ($v['record_type']==6){
                    $record_type_name='订单取消';
                    $operation='+';
                }elseif ($v['record_type']==7){
                    $record_type_name='盘亏下调';
                    $operation='-';
                }elseif ($v['record_type']==8){
                    $record_type_name='盘盈上调';
                    $operation='+';
                }elseif ($v['record_type']==9){
                    $record_type_name='重新销售';
                    $operation='+';
                }elseif ($v['record_type']==10){
                    $record_type_name='商品下单';
                    $operation='-';
                }elseif ($v['record_type']==11){
                    $record_type_name='调仓入库';
                    $operation='-';
                }elseif ($v['record_type']==12){
                    $record_type_name='调仓出库';
                    $operation='+';
                }elseif ($v['record_type']==13){
                    $record_type_name='退货退款';
                    $operation='+';
                }elseif ($v['record_type']==15){
                    $record_type_name='商品取消';
                    $operation='+';
                }elseif ($v['record_type']==16){
                    $record_type_name='漏货退款';
                    $operation='+';
                }elseif ($v['record_type']==17){
                    $record_type_name='在仓回流';
                    $operation='+';
                }elseif ($v['record_type']==18){
                    $record_type_name='盘点正常';
                    $operation='/';
                }elseif ($v['record_type']==19){
                    $record_type_name='调仓取消';
                    $operation='+';
                }elseif ($v['record_type']==20){
                    $record_type_name='直接出库';
                    $operation='-';
                }elseif ($v['record_type']==21){
                    $record_type_name='直接出库-活动';
                    $operation='-';
                }elseif ($v['record_type']==22){
                    $record_type_name='直接出库-试新';
                    $operation='-';
                }elseif ($v['record_type']==23){
                    $record_type_name='直接出库-特殊调拨';
                    $operation='-';
                }elseif ($v['record_type']==24){
                    $record_type_name='直接出库-礼盒';
                    $operation='-';
                }elseif ($v['record_type']==25){
                    $record_type_name='直接出库-果盘';
                    $operation='-';
                }elseif ($v['record_type']==26){
                    $record_type_name='直接出库-赠品';
                    $operation='-';
                }elseif ($v['record_type']==27){
                    $record_type_name='直接出库-送客户';
                    $operation='-';
                }elseif ($v['record_type']==28){
                    $record_type_name='直接出库-内部处理';
                    $operation='-';
                }elseif ($v['record_type']==29){
                    $record_type_name='对消减少';
                    $operation='-';
                }elseif ($v['record_type']==30){
                    $record_type_name='对消增加';
                    $operation='+';
                }elseif ($v['record_type']==31){
                    $record_type_name='直接出库-批发';
                    $operation='-';
                }elseif ($v['record_type']==32){
                    $record_type_name='直接出库-退货';
                    $operation='-';
                }
                $list[$k]['record_type_name']=$record_type_name;
                $list[$k]['operation']=$operation;
                $operation_username=$this->get_username($v['operation_userid']);
                if($operation_username){
                    $list[$k]['operation_username']=$operation_username;
                }else{
                    $operation_username=$this->check_whether_average($v['average_userid']);
                    $list[$k]['operation_username']=$operation_username;
                }

                $list[$k]['operation_addtime']=local_date('Y-m-d H:i:s',$v['operation_addtime']);

                $str = "商品名称：".$list[$k]['goods_name']
                    ."\n类型数量：" .$list[$k]['record_type_name']." [ ".$list[$k]['operation'].$list[$k]['operation_num']." ] "
                    ."\n剩余数量：".$list[$k]['real_num']
                    ."\n    操作者：".$list[$k]['operation_username']." [ ".$list[$k]['operation_addtime']." ] ";
                array_push($data['list'],$str);
            }
            $data['is_last'] =1 ;
            returnApiSuccess($data,"已返回");
        }else{
            returnApiError("无记录");
        }
    }


    /**
     * TODO 盘点暂存记录
     * @param $goods_id
     * @param $shelf_num
     */
    public function show_pd_cache($goods_id, $shelf_num,$wid){
        $shelf_date = explode("-",$shelf_num);

        if(count($shelf_date)>1){
            $sh_id = M("shelves")->where(array("shelves_sn"=>$shelf_date[0],"wid"=>$wid))->getField("id");
            $cache_data = M("take_stock_inventory_cache")
                ->where(array("goods_id"=>$goods_id,"sh_id"=>$sh_id,"line"=>$shelf_date[1]))
                ->order('ctime desc')->limit(100)
                ->select();
            $data['list'] = array();

            //array_push($data['list'],M("take_stock_inventory_cache")->getLastSql());
            foreach ($cache_data as $key=>$value){
                if($value['type']==1){
                    $type="已提交";
                }else{
                    $type="已缓存";
                }
                $str = "货架：".$shelf_num
                    ."\n商品：" .$value['goods_name']." [ ".$value['goods_sn']." ] "
                    ."\n类型：".$type
                    ."\n数量：".$value['now_number']
                    ."\n操作：".$value['user']." [ ".local_date('Y-m-d H:i:s', $value['ctime'])." ] ";
                array_push($data['list'],$str);
            }
            $data['is_last'] =1 ;
            returnApiSuccess($data,"已返回");
        }else{
            returnApiError("货架编号错误");
        }


    }

    /**
     * TODO 获取VIP价格
     * @param $goods_id
     * @param $shop_price
     * @return mixed
     */
    private function get_vip_price($goods_id, $shop_price){
        $price = D('member_price')->where(array('goods_id' => $goods_id, 'user_rank' => 2))->getField('user_price');

        if (!$price) {
            $price = $shop_price * M('user_rank')->where(array('rank_id' => 2))->getField('discount');
            return $price;
        }
        return $price;
    }

    /**
     * todo 获取仓库
     * @param $id
     * @return mixed
     */
    private function get_warehousename($id){
        $result = M('warehouse')->where('id='.$id)->find();
        return $result;
    }


    /**
     * todo 设置盘点数量
     */
    public function  set_check_count($user_id,$goods_id,$check_count,$content,$is_ok,$shelf=true){
        //是否内部调用、
        if($shelf){
            $user_id=I('post.user_id','intval');            //用户ID
            $goods_id=I('post.good_id','intval');          //商品ID
            $check_count=I('post.check_count','intval');    //盘点数量  在仓数量
            $content=I('post.content','');                  //盘点备注
            $is_ok=I('post.is_ok','');                      //是否盘点正常  1为盘点正常
        }

        //returnApiError($check_count);
        //exit();
//        dump($user_id);
//        dump($goods_id);
//        dump($check_count);
//        dump($content);
//        dump($is_ok);
//        exit();

        if(empty($user_id)){
            if($shelf){
                returnApiError('UID 为空');
            }else{
                $data['state'] = false;
                $data['msg'] = 'UID 为空';
                return $data;
            }

        }
        if (empty($goods_id)){
            if($shelf){
                returnApiError("商品ID未找到");
            }else{
                $data['state'] = false;
                $data['msg'] = '商品ID未找到';
                return $data;
            }
        }

        $wid = $this->get_user_wid_identity($user_id);
        $user_name=M('admin_user')->where(array('user_id'=>$user_id))->getField('user_name');
        $where="gs.wid=".$wid." and gs.goods_id = '".$goods_id."' and gs.goods_id=g.goods_id";
        $list=M('')->table('sdx_goods_storage as gs,sdx_goods as g')
            ->field('gs.id,gs.goods_id,g.goods_name,gs.goods_sn,gs.wid,gs.practical_num,gs.freeze_num,gs.inferior_quality_num,(gs.practical_num+gs.freeze_num) as in_warehouse_num')
            ->where($where)->find();
        if($list){
            $batch_sn = $this->get_batch_sn("PD");
            $tsirdata=array(
                'batch_sn'=>$batch_sn,
                'operation_userid'=>$user_id,
                'operation_addtime'=>gmtime(),
                'backflow_documents_pic'=>'',
                'documents_remark'=>$content
            );

            //生成盘点记录
            $tsirid=M('take_stock_inventory_record')->add($tsirdata);

            if($tsirid){
                $tsirddata=array(
                    'tsir_id'=>$tsirid,
                    'batch_sn'=>$batch_sn,
                    'goods_storage_id'=>$list['id'],
                    'wid'=>$wid,
                    'goods_id'=>$list['goods_id'],
                    'goods_sn'=>$list['goods_sn'],
                    'goods_name'=>$list['goods_name'],
                    'add_time'=>gmtime()
                );


                if($is_ok==1) {
                    $tsirddata['operation_type'] = 2;
                    $tsirddata['take_stock_num'] = 0;
                    $tsirddata['real_num'] = $list['practical_num'];
                    //生成盘点记录
                    $tsirdid=M('take_stock_inventory_record_detail')->add($tsirddata);

                    //未变 新增未变记录
                    $gsrdata = array(
                        'goods_storage_id' => $list['id'],
                        'wpid' => 0,
                        'wid' => $wid,
                        'goods_id' => $list['goods_id'],
                        'goods_sn' => $list['goods_sn'],
                        'operation_num' => 0,
                        'real_num' => $list['practical_num'],
                        'frozen_num' => 0,
                        'defective_num' => 0,
                        'operation_userid' => $user_id,
                        'operation_addtime' => gmtime(),
                        'source_no' => $batch_sn,
                    );
                    $gsrdata['record_type'] = 18;
                    $gsrdata['remark'] = '盘点正常 [ APP ]';
                    //生成商品出入库记录
                    M('goods_storage_record')->add($gsrdata);
//                    if($list['practical_num']>0){
//                        $og=array(
//                            'wid'=>$wid,
//                            'goods_id'=>$list['goods_id'],
//                            'practical_num'=>$list['practical_num'],
//                            'freeze_num'=>$list['freeze_num'],
//                            'goods_storage_id'=>$list['id'],
//                            'procurement_id'=>0,
//                            'quantity_type'=>'仓管端盘点',
//                            'user_name'=>$user_name,
//                            'batch_no'=>$batch_sn,
//                        );
//                        //检查是否存在预售订单商品，若存在，进行实际库存操作
//                        $this->check_goods_order_quantity($og);
                    if($shelf) {
                        returnApiSuccess(null, $tsirid.'成功'.$tsirdid);
                    }else{
                        //return true;
                        $data['state'] = true;
                        $data['msg'] = 'true';
                        return $data;
                    }
                }



                $in_dj_num = $this->get_good_zz_dy($list['goods_id'],$wid);//在仓订单冻余
                $in_dj_num_dc = $this->get_good_zc_dy_dc($list['goods_id'],$wid);//在仓调仓冻余
                //$dc_num = $this->get_good_dc_dy($list['goods_id'],$wid);  //调仓冻库
                $new_real_num = $check_count - $in_dj_num - $in_dj_num_dc;//新实余 = 在仓库存 - 在仓冻余

                if($new_real_num<=0){
                    //新实于小于等于0
                    $tsirddata['operation_type']=0;
                    $tsirddata['take_stock_num']=$check_count;
                    $tsirddata['real_num']=0;
                }
                if($new_real_num>$list['practical_num']){
                    //新实于大于原实于
                    $tsirddata['operation_type']=1;
                    $tsirddata['take_stock_num']=$new_real_num - $list['practical_num'];
                    $tsirddata['real_num']=$new_real_num;
                }

                if($new_real_num<$list['practical_num']&&$new_real_num>0){
                    $tsirddata['operation_type']=0;
                    $tsirddata['take_stock_num']=$list['practical_num'] -$new_real_num;
                    $tsirddata['real_num']=$new_real_num;
                }
                if($new_real_num == $list['practical_num']){
                    $tsirddata['operation_type']=2;
                    $tsirddata['take_stock_num']=0;
                    $tsirddata['real_num']=$new_real_num;
                    //returnApiSuccess($tsirddata);
                }

//                $tsirddata['take_stock_num']=$new_real_num;



                //生成盘点记录明细
                $tsirdid=M('take_stock_inventory_record_detail')->add($tsirddata);


                if($tsirdid){
                    if($tsirddata['operation_type']==1){// 盘盈，实际库存数加
                        $updatedata=array('practical_num'=>$tsirddata['real_num']);
                    }else if($tsirddata['operation_type']==0){  //盘亏，实际库存数减
                        $updatedata=array('practical_num'=>$tsirddata['real_num']);
                    }else if($tsirddata['operation_type']==2){  //盘亏，实际库存数减
                    }

                    if($tsirddata['operation_type']==2){
                        //未变 新增未变记录
                        $gsrdata=array(
                            'goods_storage_id'=>$list['id'],
                            'wpid'=>0,
                            'wid'=>$wid,
                            'goods_id'=>$list['goods_id'],
                            'goods_sn'=>$list['goods_sn'],
                            'operation_num'=>0,
                            'real_num'=>$list['practical_num'],
                            'frozen_num'=>0,
                            'defective_num'=>0,
                            'operation_userid'=>$user_id,
                            'operation_addtime'=>gmtime(),
                            'source_no'=>$batch_sn,
                        );
                        $gsrdata['record_type']=18;
                        $gsrdata['remark']='盘点正常 [ APP ]';
                        //生成商品出入库记录
                        M('goods_storage_record')->add($gsrdata);
                        //if($list['practical_num']>0){
                            $og=array(
                                'wid'=>$wid,
                                'goods_id'=>$list['goods_id'],
                                'practical_num'=>$list['practical_num'],
                                'freeze_num'=>$list['freeze_num'],
                                'goods_storage_id'=>$list['id'],
                                'procurement_id'=>0,
                                'quantity_type'=>'仓管端盘点',
                                'user_name'=>$user_name,
                                'batch_no'=>$batch_sn,
                            );
                            //检查是否存在预售订单商品，若存在，进行实际库存操作
                            $this->check_goods_order_quantity($og);
//                        }else{
//                            if($shelf) {
//                                returnApiError("错误：4");
//                            }else{
//                                $data['state'] = false;
//                                $data['msg'] = '错误：4';
//                                return $data;
//                            }
//                        }
                        if($shelf) {
                            returnApiSuccess(null,'成功');
                        }else{
                            $data['state'] = true;
                            $data['msg'] = '成功';
                            return $data;
                        }
                    }else{
                        //修改实际库存数

                        $goods_storage_sql = M('goods_storage')->where(array('wid'=>$wid,'goods_id'=>$list['goods_id']))->save($updatedata);
                        if($goods_storage_sql !== FALSE){
                            //更新实际库存缓存
                            set_goods_practical_num_cache($list['goods_id'],$wid,$updatedata['practical_num']);
                            //更新队列库存缓存
                            set_queue_goods_stock($list['goods_id'],$wid,$updatedata['practical_num']);
                            $gsrdata=array(
                                'goods_storage_id'=>$list['id'],
                                'wpid'=>0,
                                'wid'=>$wid,
                                'goods_id'=>$list['goods_id'],
                                'goods_sn'=>$list['goods_sn'],
                                'operation_num'=>$tsirddata['take_stock_num'],
                                'real_num'=>$updatedata['practical_num'],
                                'frozen_num'=>0,
                                'defective_num'=>0,
                                'operation_userid'=>$user_id,
                                'operation_addtime'=>gmtime(),
                                'source_no'=>$batch_sn,
                            );
                            if($tsirddata['operation_type']==1){
                                $gsrdata['record_type']=8;
                                $gsrdata['remark']='盘盈上调 [ APP ]';
                            }else if($tsirddata['operation_type']==0){
                                $gsrdata['record_type']=7;
                                $gsrdata['remark']='盘亏下调 [ APP ]';
                            }
                            //生成商品出入库记录
                            M('goods_storage_record')->add($gsrdata);
                            if($updatedata['practical_num']>0){
                                $og=array(
                                    'wid'=>$wid,
                                    'goods_id'=>$list['goods_id'],
                                    'practical_num'=>$updatedata['practical_num'],
                                    'freeze_num'=>$list['freeze_num'],
                                    'goods_storage_id'=>$list['id'],
                                    'procurement_id'=>0,
                                    'quantity_type'=>'仓管端盘点',
                                    'user_name'=>$user_name,
                                    'batch_no'=>$batch_sn,
                                );
                                //检查是否存在预售订单商品，若存在，进行实际库存操作
                                $this->check_goods_order_quantity($og);
                            }
                            if($shelf) {
                                returnApiSuccess(null,'成功');
                            }else{
                                $data['state'] = true;
                                $data['msg'] = '成功';
                                return $data;
                            }
                        }else{
                            if($shelf) {
                                returnApiError("错误：3  ".M('goods_storage')->getlastsql());
                            }else{
                                $data['state'] = false;
                                $data['msg'] = '错误：3';
                                return $data;
                            }
                        }
                    }
                }else{
                    if($shelf) {
                        returnApiError("错误：1");
                    }else{
                        return false;
                    }
                }
            }else{
                if($shelf) {
                    returnApiError("错误：2");
                }else{
                    return false;
                }
            }

        }else{
            if($shelf) {
                returnApiError("本仓库未找到此商品");
            }else{
                return false;
            }
        }
    }


    /*
      * todo 处理预售下单商品，并扣实际库存
      *
      * */
    private function check_goods_order_quantity($og=array()){  //$wid,$goods_id,$ruku_num,$goods_storage_id=0
        ini_set('max_execution_time', '0');
        set_time_limit(0);
        $order=M('')->table(C ( 'DB_PREFIX' ).'order_goods as og,'.C ( 'DB_PREFIX' ) .'order_info as oi')
            ->field('og.rec_id,og.goods_id,og.goods_sn,og.goods_name,og.goods_number,og.is_presell,og.buckle_inventory,og.order_id,oi.user_id,oi.order_sn,oi.order_sn,oi.order_status,oi.pay_status,oi.shipping_status,oi.shipping_id')
            ->where('oi.order_id=og.order_id and (oi.order_status NOT IN (0,2,3)) and oi.wid='.$og['wid'].' and og.goods_id='.$og['goods_id']." and oi.is_presell=1 and og.buckle_inventory=0 and oi.best_time >= UNIX_TIMESTAMP(date_format(now(), '%Y-%m-%d 00:00:00')) and oi.best_time < UNIX_TIMESTAMP(date_format(now(), '%Y-%m-%d 23:59:59')) and ( (oi.shipping_id!=2 and oi.shipping_status=0) or (oi.shipping_id=2 and (oi.shipping_status in (0,1))))")
            ->order('oi.best_time asc,oi.order_id asc')
            ->select();
        if($order){
            $refund_detail=M('refund_detail');
            $goods_storage=M('goods_storage');
            $goods_storage_record=M('goods_storage_record');
            $goods_freeze_record=M('goods_freeze_record');
            $order_goods=M('order_goods');
            $order_info=M('order_info');
            $order_action=M('order_action');
            foreach ($order as $k=>$v){
                if($v['is_presell']==1 && $v['buckle_inventory']==0){
                    $refund_number=0;
                    /*
                     * //检查退货退款时是否已经的处理，若有，该操作则进行对扣比较操作
                     * */
                    $rdlist=$refund_detail->field('goods_id,SUM(refund_number) as refund_number')
                        ->where(array('order_id'=>$v['order_id'],'goods_id'=>$v['goods_id']))
                        ->find();
                    if($rdlist['refund_number']>0){
                        $v['goods_number']=$v['goods_number']-ceil($rdlist['refund_number']);//需要补齐数=购买数量-退款数量
                    }
                    //获取实际库存缓存
                    $cahce_goods_practical_num = get_goods_practical_num_cache($og['goods_id'],$og['wid'],$og['practical_num']);
                    //获取队列库存缓存
                    $cache_queue_goods_stock = get_queue_goods_stock($og['goods_id'],$og['wid']);
                    if($og['practical_num']>=$v['goods_number']){
                        $og['practical_num']=$og['practical_num']-$v['goods_number'];
                        $og['freeze_num']=$og['freeze_num']+$v['goods_number'];
                        $data=array('practical_num'=>$og['practical_num'],'freeze_num'=>$og['freeze_num']);
                        //减实际库存
                        $gsid=$goods_storage->where(array('wid'=>$og['wid'],'goods_id'=>$v['goods_id']))->save($data);
                        if($gsid){
                            //更新实际库存缓存
                            set_goods_practical_num_cache($og['goods_id'],$og['wid'],$cahce_goods_practical_num-$v['goods_number']);
                            //更新队列库存缓存
                            set_queue_goods_stock($og['goods_id'],$og['wid'],$cache_queue_goods_stock-$v['goods_number']);
                            $gsrdata=array(
                                'goods_storage_id'=>$og['goods_storage_id'],
                                'wpid'=>$og['procurement_id'],
                                'goods_id'=>$v['goods_id'],
                                'goods_sn'=>$v['goods_sn'],
                                'operation_num'=>$v['goods_number'],
                                'real_num'=>$og['practical_num'],
                                'frozen_num'=>0,
                                'defective_num'=>0,
                                'operation_userid'=>0,
                                'average_userid'=>$v['user_id'],
                                'operation_addtime'=>gmtime(),
                                'source_no'=>$v['order_sn'],
                                'record_type'=>10,
                                'remark'=>'商品下单',
                            );
                            //商品库存出入库记录
                            $goods_storage_record->add($gsrdata);
                            $gfrdata=array(
                                'goods_storage_id'=>$og['goods_storage_id'],
                                'wid'=>$og['wid'],
                                'goods_id'=>$v['goods_id'],
                                'goods_sn'=>$v['goods_sn'],
                                'goods_name'=>$v['goods_name'],
                                'freeze_num'=>$v['goods_number'],
                                'real_num'=>0,
                                'frozen_num'=>$og['freeze_num'],
                                'defective_num'=>0,
                                'operation_userid'=>0,
                                'average_userid'=>$v['user_id'],
                                'operation_addtime'=>gmtime(),
                                'source_no'=>$v['order_sn'],
                                'record_type'=>4,
                                'remark'=>'商品下单',
                            );
                            //生成商品库存冻结记录
                            $goods_freeze_record->add($gfrdata);
                            //修改订单商品实际库存已补齐
                            $order_goods->where(array('rec_id'=>$v['rec_id']))->save(array('buckle_inventory'=>1));

                            $order_action_data=array(
                                'order_id'=>$v['order_id'],
                                'action_user'=>$og['user_name'],
                                'order_status'=>$v['order_status'],
                                'shipping_status'=>$v['shipping_status'],
                                'pay_status'=>$v['pay_status'],
                                'action_place'=>0,
                                'action_note'=>$og['quantity_type'].'-补齐<br />来源批次号：'.$og['batch_no'].'<br /> 商品：'.$v['goods_name'].'(货号:'.$v['goods_sn'].')(ID:'.$v['goods_id'].')',
                                'log_time'=>gmtime(),
                            );
                            //生成订单处理日志
                            $order_action->add($order_action_data);

                            if($this->check_ordergoods_buckle_inventory($v['order_id'],$og['wid'])){
                                //修改该订单商品实际库存已补齐
                                if($v['shipping_id']==2){
                                    $update_order=array('buckle_inventory'=>1,'shipping_status'=>1);
                                }else{
                                    $update_order=array('buckle_inventory'=>1);
                                }
                                $order_info->where(array('order_id'=>$v['order_id']))->save($update_order);
                                $order_action_data=array(
                                    'order_id'=>$v['order_id'],
                                    'action_user'=>$og['user_name'],
                                    'order_status'=>$v['order_status'],
                                    'shipping_status'=>$v['shipping_status'],
                                    'pay_status'=>$v['pay_status'],
                                    'action_place'=>0,
                                    'action_note'=>'全单已补齐，转为现售单',
                                    'log_time'=>gmtime(),
                                );
                                $order_action->add($order_action_data);
                            }


                        }
                    }else{
                        continue;
                    }
                }else{
                    continue;
                }
            }
            return true;
        }else{
            return false;
        }
    }

    // todo 检查该订单商品库存是否全部补齐
    private function check_ordergoods_buckle_inventory($order_id=0,$wid=0){
        $count=M('')->table(C ( 'DB_PREFIX' ).'order_goods as og,'.C ( 'DB_PREFIX' ).'order_info as oi')
            ->where('oi.order_id=og.order_id and og.order_id='.$order_id.' and oi.wid='.$wid.' and og.is_presell=1 and og.buckle_inventory=0 and ( (oi.shipping_id!=2 and oi.shipping_status=0) or (oi.shipping_id=2 and (oi.shipping_status in (0,1))) )')
            ->count();
        if($count==0){
            return true;
        }else{
            return false;
        }
    }

    /**
     * todo 生成批次号
     * @param $prefix
     * @return string
     */
    private function get_batch_sn($prefix){
        /* 选择一个随机的方案 */
        mt_srand((double) microtime() * 1000000);

        return $prefix.date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }

    /**
     * todo 货架管理-详情
     * rui poptser@foxmail.com 2016-11-30 11:32:22
     */
    public function shelf_detail(){
        $user_id=I('post.user_id','intval');            //用户ID
        $shelf_num=I('post.shelf_num','');              //货架编号
        //检测是否属于货架与货架列的组合
        $shelf_date = explode("-",$shelf_num);
        $is_line = false;
        if(is_numeric($shelf_date[1])){
            //是货架与列的组合
            $shelf_num = $shelf_date[0];
            $is_line = true;
        }
        $wid = $this->get_user_wid_identity($user_id);
        $model = M();
        $sql = "SELECT sh.id AS sh_id,sh.sort AS list_num,sc.name AS shelf_tag,sl.name AS shelf_type,wh.name AS shelf_store,sh.state AS shelf_state,
                sh.shelves_sn AS shelf_num,sh.s_floor AS shelf_row,sh.wid AS shelf_store_id,
                sh.category_id AS shelf_tag_id,sh.class_id AS shelf_type_id
                FROM sdx_shelves AS sh,sdx_shelves_cat AS sc,sdx_shelves_class AS sl ,sdx_warehouse AS wh WHERE 
                sh.category_id = sc.id AND sh.class_id = sl.id AND sh.wid =  wh.id AND sh.wid = ".$wid." AND sh.shelves_sn = '".$shelf_num."' LIMIT 1 ";
        $list = $model->query($sql);
        if($list[0]){
            $data['data'] = $list[0];
            if($shelf_date[1]>$data['data']['shelf_row']){
                returnApiError("此货架列数错误，请先管理列数\n{$shelf_num} 目前 {$data['data']['shelf_row']} 列");
            }else{
                if($is_line){
                    //是货架与列的组合
                    $data['is_row'] = 1;
                    $data['in_row'] = $shelf_date[1];
                }else{
                    $data['is_row'] = 0;
                }

                //在架商品种类，在货架上一共多少种商品
                if($is_line){
                    $goods_sn_list = M("shelves_goods")->where(array("sh_id"=>$list[0]['sh_id'],"sh_floor"=>$shelf_date[1]))->group("goods_sn")->getField("goods_sn",true);
                }else{
                    $goods_sn_list = M("shelves_goods")->where(array("sh_id"=>$list[0]['sh_id']))->group("goods_sn")->getField("goods_sn",true);
                }

                foreach ($goods_sn_list as $key=>$value){
                    if(M("goods")->where(array("goods_sn"=>$value))->count()==0){
                        unset($goods_sn_list[$key]);
                    }
                }


                $data['data']['count_goods_type'] = count($goods_sn_list);

                returnApiSuccess($data,"数据已返回");
            }
        } else {
            returnApiError("未获取到数据");
        }
    }
    /**
     * todo 货架管理- 商品绑定
     * rui poptser@foxmail.com 2016-11-30 11:32:32
     */
    public function shelf_bind_goods(){
        $user_id=I('post.user_id','intval');            //用户ID
        $shelf_num=I('post.shelf_num','');              //货架编号
        $goods_num=I('post.goods_num','');              //商品货号
        $putaway=I('post.putaway','intval');            //是否上架（0下架,1上架）
        $putaway_row=I('post.putaway_row','intval');    //货架层数
        if($putaway_row==0){
            returnApiError("无法上架至0此列");
        }

        $shelf_date = explode("-",$shelf_num);
        if($shelf_date[1]>0){
            //是货架与列的组合
            $shelf_num = $shelf_date[0];
            $putaway_row = $shelf_date[1];
        }
        $wid = $this->get_user_wid_identity($user_id);

        $shelves_data = M("shelves")->where(array("shelves_sn"=>$shelf_num,"state"=>1,"wid"=>$wid))->find();
        if(!$shelves_data){
            returnApiError("货架不存在/未启用");
        }
        if($putaway==1){
            if($shelves_data['s_floor']-$putaway_row<0){
                returnApiError("列数超出货架限制，当前限制：".$shelves_data['s_floor']);
            }
        }
        $goods_data = M("goods")->where(array("goods_sn"=>$goods_num,"is_delete"=>0))->find();
        if(!$goods_data){
            returnApiError("商品不存在/已移除");
        }
        if($putaway==0){
            //下架商品
            if($putaway_row>0){
                $Results = M("shelves_goods")->where(array("goods_sn"=>$goods_num,"sh_id"=>$shelves_data['id'],"sh_floor"=>$putaway_row))->delete();
            }else{
                $Results = M("shelves_goods")->where(array("goods_sn"=>$goods_num,"sh_id"=>$shelves_data['id']))->delete();
            }

            if($Results){
                $this->w_action_log($user_id,$shelves_data['id'],6,$goods_data['goods_name'],$goods_num,$putaway_row);
                //查询该商品是否在其他货架上面存在，若其他货架上面没有该商品，则自动将商品库对应的该商品从“上架”转变为“下架”。
                $count=M('shelves_goods')->alias('sg')
                       ->join(C('DB_PREFIX').'shelves as s on sg.sh_id=s.id and s.wid='.$wid)
                       ->where(array("sg.goods_sn"=>$goods_num))
                       ->count("sg.id");
                if($count<=0){
                    //根据商品货号修改该商品上下架状态，并且写入修改该商品上下架操作日志
                    $this->update_goods_is_on_sale($goods_num,0,$user_id,$wid);
                }
                returnApiSuccess(null,"下架成功");
            }else{
                returnApiError("无此商品/下架失败".M("shelves_goods")->getlastsql());
            }
        }elseif ($putaway==1){
            //上架商品
            $Resultp = M("shelves_goods")->where(array("goods_sn"=>$goods_num,"sh_id"=>$shelves_data['id'],"sh_floor"=>$putaway_row))->find();
            if($Resultp){
                //根据商品货号修改该商品上下架状态，并且写入修改该商品上下架操作日志
                $this->update_goods_is_on_sale($goods_num,1,$user_id,$wid);
                returnApiError("本货架当前列已存在此商品");
            }else{
                $user_info = A("Distribution")->get_admin_user_name($user_id);
                $data['goods_sn'] = $goods_num;
                $data['sh_id'] = $shelves_data['id'];
                $data['sh_floor'] = $putaway_row;
                $data['add_time'] = gmtime();
                $data['add_user'] = $user_info['user_name'];
                $Result = M("shelves_goods")->add($data);
                if($Result){
                    //加入操作记录 $user_name,$sh_id,$type,$goods_name,$goods_sn
                    $this->w_action_log($user_id,$shelves_data['id'],5,$goods_data['goods_name'],$goods_num,$putaway_row);
                    //根据商品货号修改该商品上下架状态，并且写入修改该商品上下架操作日志
                    $this->update_goods_is_on_sale($goods_num,1,$user_id,$wid);
                    returnApiSuccess(null,"上架成功");
                }else{
                    returnApiError("上架失败");
                }
            }
        }else{
            returnApiError("操作内容错误");
        }
    }
    
     /*
     * 根据商品货号修改该商品上下架状态，并且写入修改该商品上下架操作日志
     * */
    private function  update_goods_is_on_sale($goods_sn='',$is_on_sale='',$user_id=0,$wid){
        if($is_on_sale==0){
            //取消商品下架关联
            return true;
        }
        if(!empty($goods_sn)){
            $goods_mod=M('goods_wid_'.$wid);
            $where=array('goods_sn'=>$goods_sn);
            $goodsdata=$goods_mod->field('goods_id,is_on_sale')->where($where)->find();
            if($goodsdata['goods_id']>0){
                $goods_save_id=$goods_mod->where(array('goods_id'=>$goodsdata['goods_id']))->save(array('is_on_sale'=>$is_on_sale));
                if($goods_save_id!==false){
                    if($goodsdata['is_on_sale']!=$is_on_sale){
                        $old_value=$this->is_on_sale_name($goodsdata['is_on_sale']);
                        $new_value=$this->is_on_sale_name($is_on_sale);
                        $gaction_data=array(
                                     'goods_id'=>$goodsdata['goods_id'],
                                     'action_user'=>$this->get_username($user_id),
                                     'action_time'=>gmtime(),
                                     'action_type'=>'是否上架',
                                     'old_value'=>$old_value,
                                     'new_value'=>$new_value
                        );
                        M('goods_action')->add($gaction_data);
                    }
                }
            }
        }
    }
    
    private function is_on_sale_name($is_on_sale){
        if($is_on_sale==0){
            $name='下架';
        }else if ($is_on_sale==1){
            $name='上架';
        }else{
            $name="";
        }
        return $name;
    }

    /**
     * todo 货架启动开关
     * rui poptser@foxmail.com 2016-11-30 11:32:39
     */
    public function shelf_open(){
        $user_id=I('post.user_id','intval');            //用户ID
        $shelf_num=I('post.shelf_num','intval');        //货架编号
        $open=I('post.open','intval');                  //是否上架（0禁止,1启用）

        $shelf_date = explode("-",$shelf_num);
        if(is_numeric($shelf_date[1])){
            //是货架与列的组合
            $shelf_num = $shelf_date[0];
        }
        $wid = $this->get_user_wid_identity($user_id);
        if(empty($shelf_num)||!isset($open)){
            returnApiError("货架编号/开关指令 不存在");
        }
        $Result = M("shelves")->where(array("shelves_sn"=>$shelf_num,"wid"=>$wid))->setField('state',$open);
        if($Result){
            $sh_id = M("shelves")->where(array("shelves_sn"=>$shelf_num,"wid"=>$wid))->getField('id');
            if($open==1){
                $this->w_action_log($user_id,$sh_id,3);
            }else{
                $this->w_action_log($user_id,$sh_id,4);
            }

            returnApiSuccess(null,"成功修状态");
        }else{
            returnApiError("修改失败");
        }
    }

    /**
     * todo 货架配置[返回仓库列表，货架类型列表，货架用途列表]
     * rui poptser@foxmail.com 2016-11-30 11:38:29
     */
    public function shelf_config(){
        $where['status'] = 1;
        $where['id'] = $this->get_user_wid_identity(I('post.user_id','intval'));
        $data['list_store']=M("warehouse")->field('id,name')->where($where)->select();
        $data['list_tag']=M("shelves_cat")->field('id,name')->select();
        $data['list_type']=M("shelves_class")->field('id,name')->select();
        returnApiSuccess($data,"已返回数据");
    }

    /**
     * todo 新建货架
     * rui poptser@foxmail.com 2016-11-30 11:51:08
     */
    public function shelf_create(){
        $user_id=I('post.user_id','intval');    //用户ID
        $wid = I('post.store_id','');           //仓库ID
        $category_id=I('post.tag_id','');       //使用类型ID
        $class_id=I('post.type_id','');         //货架类型ID
        $s_floor=I('post.shelf_row','');      //货架一共列数
        $list_num=I('post.list_num','');      //货架排序

        if($list_num<1){
            $list_num = 1;
        }

        $user_info = A("Distribution")->get_admin_user_name($user_id);

        $data['wid'] = $wid;
        $data['category_id'] = $category_id;
        $data['class_id'] = $class_id;
        $data['s_floor'] = $s_floor;
        $data['add_user'] = $user_info['user_name'];
        $data['state'] = 1;
        $data['add_time'] = gmtime();
        $data['sort'] = $list_num;

        $cat = M("shelves_cat")->where(array("id"=>$category_id))->getField('tag');
        $class = M("shelves_class")->where(array("id"=>$class_id))->getField('tag');

        $where['class_id'] = $where_2['class_id'] = $class_id;
        $where['category_id'] = $where_2['category_id'] = $category_id;
        $where['wid'] = $where_2['wid'] = $wid;;


        $all_num = M("shelves")->where($where)->order("id desc")->getField('shelves_sn');
        if($all_num){
            preg_match('/\d+/',$all_num,$arr);
            $new_shelves_sn = $cat.$class.($arr[0]+1);
        }else{
            preg_match('/\d+/',$all_num,$arr);
            $new_shelves_sn = $cat.$class."1";
        }

        $where_2['shelves_sn'] = $new_shelves_sn;
        $is_use = M("shelves")->where($where_2)->count();
        if($is_use>0){
            returnApiError("新建货架失败");
        }else{
            $data['shelves_sn'] = $new_shelves_sn;
        }

        //查询出需要调整的货架
        $where_s['wid'] = $wid;
        $where_s['sort'] = array("gt",$list_num-1);
        $all_id = M("shelves")->where($where_s)->order("sort ASC,id DESC")->getField('id',true);


        $Result = M("shelves")->add($data);
        if($Result){
            //重排货架序号
            $action_id = $this->w_sh_sort($user_id,$Result,8);
            foreach ($all_id as $key=>$value){
                $action_details['action_id'] = $action_id;
                $action_details['sh_id'] = $value;
                $action_details['sort'] = $key+$list_num+1;
                $action_details['type'] = 8;
                M("shelves_action_details")->add($action_details);
            }

            $re_data['shelf_num'] = $data['shelves_sn'];
            $this->w_action_log($user_id,$Result,1);
            returnApiSuccess($re_data,'新建成功，已返回货架编号');
        }else{
            returnApiError("新建货架失败");
        }
    }

    /**
     * todo 货架列表页
     * rui poptser@foxmail.com 2017年1月17日15:52:14
     */
    public function shelf_list(){
        $user_id=I('post.user_id','intval');            //用户ID
        $is_fast=I('post.is_fast','intval');            //是否仅返回列表
        $is_no_goods=I('post.is_no_goods','intval');            //是否仅显示有商品的货架
        $is_checked=I('post.is_checked','intval');            //是否仅显示有未盘点商品的货架
        $wid = $this->get_user_wid_identity($user_id);
        $model = M();
        $sql = "SELECT sh.id AS shelf_id,sc.name AS shelf_tag,sl.name AS shelf_type,wh.name AS shelf_store,sh.state AS shelf_state,
                sh.shelves_sn AS shelf_num,sh.s_floor AS shelf_row,sh.wid AS shelf_store_id,
                sh.category_id AS shelf_tag_id,sh.class_id AS shelf_type_id,sh.sort
                FROM sdx_shelves AS sh,sdx_shelves_cat AS sc,sdx_shelves_class AS sl ,sdx_warehouse AS wh WHERE 
                sh.category_id = sc.id AND sh.class_id = sl.id AND sh.wid =  wh.id AND sh.wid = ".$wid." ORDER BY sh.sort ASC";
        $list = $model->query($sql);

        if($list){
            foreach ($list as $key=>$value){
                if($is_fast!=1){
                    //此货架一共存放商品种类数
                    $sql_num ="SELECT COUNT(*) AS num FROM  (SELECT count(*) FROM sdx_goods AS g ,sdx_shelves_goods AS sg WHERE g.goods_sn = sg.goods_sn AND sg.sh_id= ".$value['shelf_id']." GROUP BY sg.goods_sn) u";
                    $list_num = $model->query($sql_num);
                    $list[$key]['count_goods_type'] = $list_num[0]['num'];
                    $i = 0;
                    if($list_num[0]['num']>0){
                        //此货架今日未盘点商品种类数//此货架所有商品
                        $goods_list = M("shelves_goods")->where(array("sh_id"=>$value['shelf_id']))->group("goods_sn")->getField("goods_sn",true);


                        foreach ($goods_list as $key2=>$value2){
                            if(M("goods")->where(array("goods_sn"=>$value2))->count()){
                                $line_array = M("shelves_goods")->where(array("sh_id"=>$value['shelf_id'],"goods_sn"=>$value2))->getField("sh_floor",true);
                                foreach ($line_array as $value3){
                                    $is_pd = M("take_stock_inventory_cache")->where("line = ".$value3." AND TO_DAYS(from_unixtime(ctime+28800)) = TO_DAYS(now()) AND sh_id = '".$value['shelf_id']."' AND type = 1 AND goods_sn = '".$value2."'")->count();
                                    //dump(M("take_stock_inventory_cache")->getLastSql());
                                    if($is_pd==0){
                                        $i++;
                                    }
                                }
                            }
                        }
                    }
                    $list[$key]['count_no_check_goods'] = $i;
                    if($is_checked==1&&$i==0){
                        unset($list[$key]);
                    }
                }else{
                    $list[$key]['count_goods_type'] = "加载中...";
                    $list[$key]['count_no_check_goods'] = "加载中...";
                }
            }
            $data['data'] = $list;
            returnApiSuccess($data,"数据已返回");
        } else {
            returnApiError("未获取到数据");
        }

    }
    /**
     * todo 编辑货架
     * rui poptser@foxmail.com 2016-11-30 14:28:49
     */
    public function shelf_edit(){
        $user_id=I('post.user_id','intval');    //用户ID
        $wid = I('post.store_id','');           //仓库ID
        $category_id=I('post.tag_id','');       //使用类型ID
        $class_id=I('post.type_id','');         //货架类型ID
        $s_floor=I('post.shelf_row','');      //货架一共列数
        $sort=I('post.list_num','intval');      //排序位置
        $shelves_sn=I('post.shelf_num','');      //货架号

        $shelf_date = explode("-",$shelves_sn);
        if(count($shelf_date)>1){
            //是货架与列的组合
            $shelves_sn = $shelf_date[0];
        }



        $user_info = A("Distribution")->get_admin_user_name($user_id);

        //$data['wid'] = $wid;
        //$data['category_id'] = $category_id;
        //$data['class_id'] = $class_id;
        $data['s_floor'] = $s_floor;
        $data['add_user'] = $user_info['user_name'];
        $data['add_time'] = gmtime();
        $data['sort'] = $sort;
        $sh_id = M("shelves")->where(array("shelves_sn"=>$shelves_sn,"wid"=>$wid))->find();



        $where_s['wid'] = $wid;

        if($sh_id['sort']>$sort){
            //上移
            //returnApiError("上移");
            $where_s['sort'] = array("gt",$sort-1);
        }else{
            //下移
            //returnApiError("下移");
            $where_s['sort'] = array("gt",$sh_id['sort']);
            $where_s['_string'] = "sort > ".$sh_id['sort']." AND sort <= ".$sort;
        }




        $all_id = M("shelves")->where($where_s)->order("sort ASC,id DESC")->getField('id',true);


        if($sh_id['s_floor']>$s_floor){

            $new_floor = $s_floor;
            for($new_floor;$new_floor<$sh_id['s_floor'];$new_floor++){

                $action_id = $this->w_action_log_main($user_id,$sh_id['id'],6,$new_floor);
                $goods_sn_array = M("shelves_goods")->where(array("sh_id"=>$sh_id['id'],"sh_floor"=>$new_floor))->getField("goods_sn",true);

                foreach ($goods_sn_array as $value){
                    $this->w_action_log_goods($action_id,6,M("goods")->where(array("goods_sn"=>$value))->getField("goods_name"),$value);
                }
            }
            $where['sh_floor'] = array("gt",$s_floor);
            $where['sh_id'] = $sh_id['id'];
            M('shelves_goods')->where($where)->delete();
            //dump(M('shelves_goods')->getLastSql());
        }


        $action_id = $this->w_sh_sort($user_id,$sh_id['id'],8);



        if ($sh_id['sort']!=$sort){
            $action_details['action_id'] = $action_id;
            $action_details['sh_id'] = $sh_id['id'];
            $action_details['sort'] = $sort;
            $action_details['type'] = 8;
            M("shelves_action_details")->add($action_details);
        }



        $Result = M("shelves")->where(array("shelves_sn"=>$shelves_sn))->save($data);
        if($Result){
            $sh_id_new = M("shelves")->where(array("shelves_sn"=>$shelves_sn))->getField('id');
            $this->w_action_log($user_id,$sh_id_new,2);

            foreach ($all_id as $keysp=>$valuesp){
                if($valuesp==$sh_id_new){
                    unset($all_id[$keysp]);
                }
            }
            foreach ($all_id as $keys=>$values){
                if($sh_id['sort']>$sort){
                    //上移
                    $action_details['sort'] = $keys+$sort+1;
                    M("shelves")->where(array("id"=>$values))->setField('sort',$keys+$sort+1);
                }else{
                    //下移
                    $action_details['sort'] = $keys+$sh_id['sort'];
                    M("shelves")->where(array("id"=>$values))->setField('sort',$keys+$sh_id['sort']);
                }
                $action_details['action_id'] = $action_id;
                $action_details['sh_id'] = $values;
                $action_details['type'] = 8;
                M("shelves_action_details")->add($action_details);
            }


            returnApiSuccess(null,'修改成功');
        }else{
            returnApiError("修改失败");
        }
    }

    /**
     * todo 查找商品分布情况
     * rui poptser@foxmail.com 2016-11-30 14:30:32
     */
    public function check_goods_with_shelf(){
        $user_id=I('post.user_id','intval');           //用户ID
        $goods_sn=$_POST['goods_num'];              //商品货号
        $model = M();
        if(empty($goods_sn)){
            returnApiError("商品ID为空");
        }
        $is_goods = M("goods")->where(array("goods_sn"=>$goods_sn))->find();
        if(!$is_goods){
            returnApiError("无此商品".$_POST['goods_num']);
        }
        if($is_goods['is_delete']!=0){
            returnApiError("商品已删除");
        }
        $wid = $this->get_user_wid_identity($user_id);
        $sql = "SELECT sh.*,sc.name AS shelf_tag,sl.name AS shelf_type,wh.name AS shelf_store,sg.sh_floor AS putaway_row,
                sh.shelves_sn AS shelf_num
                FROM sdx_shelves AS sh,sdx_shelves_cat AS sc,sdx_shelves_class AS sl ,sdx_warehouse AS wh,sdx_shelves_goods AS sg
                WHERE 
                sh.category_id = sc.id AND sh.class_id = sl.id AND sh.wid =  wh.id AND sg.sh_id = sh.id AND sh.wid = ".$wid." 
                AND sg.goods_sn = '".$goods_sn."'";
        //echo $sql;
        $list  = $model->query($sql);
        if($list){
            $data['str_content'] = "此商品存放在：\n";
            foreach ($list as $value){
                $data['str_content'] .= $value['shelf_tag']."-".$value['shelf_type']."  编号：".$value['shelf_num']." 列：[ ".$value['putaway_row']." ]\n";
            }
            //returnApiError("222");
            returnApiSuccess($data,"数据已返回");
        } else {
            //returnApiError("111");
            $data['str_content'] = "无货架信息";
            returnApiSuccess($data,"无货架信息");
            //returnApiSuccess(null,"无货架信息");
        }
    }

    /**
     * todo 查看货架上的商品
     * rui poptser@foxmail.com 2016-12-6 10:20:57
     */
    public function shelf_goods_list(){
        $user_id=I('post.user_id','intval');           //用户ID
        $shelf_num=I('post.shelf_num','');             //货架号
        $in_row=I('post.in_row','intval');             //货架列数
        $page=I('post.page','intval');                 //页数
        $start_data = I('post.start_date');
        $end_data = I('post.end_date');
        if(empty($user_id)||empty($shelf_num)){
            returnApiError("货架号/用户ID 为空");
        }

        $shelf_date = explode("-",$shelf_num);
        if(is_numeric($shelf_date[1])){
            //是货架与列的组合
            $shelf_num = $shelf_date[0];
            $in_row = $shelf_date[1];
        }
        $wid = $this->get_user_wid_identity($user_id);

        $shelves = M("shelves");
        $shelves_id = $shelves->where(array("shelves_sn"=>$shelf_num,"wid"=>$wid))->getField('id');
        if(empty($shelves_id)){
            returnApiError("货架编号有误");
        }
        $str = "ssg.sh_id = ".$shelves_id;
        if($in_row>0){
            $str .=" and ssg.sh_floor = ".$in_row;
            $str2 = $in_row." AND ";
        }
        $str .=" and ssg.goods_sn = sg.goods_sn";
        $count=M()->table('sdx_shelves_goods as ssg,sdx_goods as sg')->field('sg.*,ssg.sh_floor')->
        where($str)->count();
//         $sql = M('order_info')->getLastSql();
        $pagearr=show_page($count, $page);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }
        $list=M()->table('sdx_shelves_goods as ssg,sdx_goods as sg')->field('sg.*,ssg.sh_floor')->
        where($str)->limit($pagearr['firstpage'].','.$pagearr['pagesize'])->select();
        if(count($list)>0){

            foreach ($list as $keys=>$values){
                $practical_num = M("goods_storage")->where(array("goods_id"=>$values['goods_id'],"wid"=>$wid))->field("practical_num,freeze_num")->find();
                //$out_dj_num = $this->get_good_cc_dy($values['goods_id']); //冻结出仓
                //$in_dj_num = $this->get_good_zz_dy($values['goods_id'],$wid);  //冻结在仓
                $in_dj_num_dc = $this->get_good_zz_dy_dc($values['goods_id'],$wid);  //冻结在仓
                if($practical_num['practical_num']>0||$in_dj_num>0){
                    //在仓库存
                    $list[$keys]['count_store'] = $practical_num['practical_num']+$in_dj_num+$in_dj_num_dc;
                }else{

                    $list[$keys]['count_store'] = 0;
                }

                $list[$keys]['is_on_sale'] = M("goods_wid_".$wid)->where(array("goods_id"=>$values['goods_id']))->getField("is_on_sale");
                if($start_data&&$end_data){
                    //筛选已盘
                    $where_cahe = $str2."(TO_DAYS(from_unixtime(ctime+28800)) BETWEEN  TO_DAYS('".$start_data."')
                      AND TO_DAYS('".$end_data."')) AND sh_id = '".$shelves_id."'
                       AND type = 1 AND goods_sn = '".$values['goods_sn']."'";
                }else{
                    //盘点时间改为上午8点为当天盘点数据
                    $where_cahe = $str2."TO_DAYS(from_unixtime(ctime+28800)) =
TO_DAYS(from_unixtime(unix_timestamp()-28800)) AND sh_id = '".$shelves_id."' AND type = 1 
                    AND goods_sn = '".$values['goods_sn']."'";
                }
                $is_pd = M("take_stock_inventory_cache")->where($where_cahe)->count();
                //dump(M("take_stock_inventory_cache")->getLastSql());
                if($is_pd==0){
                    $list[$keys]['is_check'] = 0;
                }else{
                    $list[$keys]['is_check'] = 1;
                }



            }
            returnApiSuccess(array('list'=>$list,'is_last'=>$is_last,'count'=>$count),'已经返回数据');
        }else{
            returnApiSuccess(array('list'=>array(),'is_last'=>1,'count'=>0),'无数据');
        }
    }

    /**
     * todo 写入货架记录
     * rui poptser@foxmail.com 2016-12-3 14:09:11
     * @param $user_id
     * @param $sh_id  货架ID
     * @param $type 操作类型 1 新建货架  2编辑货架 3启用货架 4禁用货架 5绑定商品 6解绑商品 7换绑商品 8 更换排序
     * @param null $goods_name
     * @param null $goods_sn
     */
    public function w_action_log($user_id,$sh_id,$type,$goods_name=null,$goods_sn=null,$s_floor=null){
        $distribute_info = A("Distribution")->get_admin_user_name($user_id);
        $data['user_id'] = $distribute_info['user_name']."( uid:".$user_id.")";
        $data['sh_id'] = $sh_id;
        //$data['goods_name'] = $goods_name;
        //$data['goods_sn'] = $goods_sn;
        $data['type'] = $type;
        $data['s_floor'] = $s_floor;
        $data['action_time'] = gmtime();
        $action_id = M("shelves_action")->add($data);
        if($type==5||$type==6||$type==7){
            $action_details['action_id'] = $action_id;
            $action_details['goods_sn'] = $goods_sn;
            $action_details['goods_name'] = $goods_name;
            $action_details['type'] = $type;
            M("shelves_action_details")->add($action_details);
        }else{
            //其他日志
        }
    }
    public function w_sh_sort($user_id,$sh_id,$type){
        $distribute_info = A("Distribution")->get_admin_user_name($user_id);
        $data['user_id'] = $distribute_info['user_name']."( uid:".$user_id.")";
        //$data['goods_name'] = $goods_name;
        //$data['goods_sn'] = $goods_sn;
        $data['type'] = $type;
        $data['sh_id'] = $sh_id;
        $data['action_time'] = gmtime();
        $action_id = M("shelves_action")->add($data);
        return $action_id;
    }


    /**
     * todo 货号批量查询商品信息
     * rui poptser@foxmail.com 2016-12-9 15:41:45
     * $array_goods_num 商品货号组，以,分割
     * goods_num goods_name img_url
     */
    public function load_goods_list(){
        $user_id=I('post.user_id','intval');           //用户ID
        $array_goods_num=I('post.array_goods_num','');             //商品货号组
        $goods_sn_array = explode(",",$array_goods_num);
        if(count($goods_sn_array)>0){
            //$where['goods_sn'] = array("in",$goods_sn_array);
            $where['is_delete'] = 0;
            foreach ($goods_sn_array as $value){
                $where['goods_sn'] = $value;
                $goods_data['data'][] = M("goods")->field('goods_id,goods_sn as goods_sn,goods_name,goods_img as goods_img')->where($where)->find();
            }
            returnApiSuccess($goods_data,"已返回数据");
        }else{
            returnApiError("无商品ID");
        }
    }

    /**
     * todo 货架管理- 商品绑定（批量）
     * rui poptser@foxmail.com 2016-12-9 15:41:45
     * $array_goods_num 商品货号组，以,分割
     * goods_num goods_name img_url
     */
    public function shelf_bind_more_goods(){
        $user_id=I('post.user_id','intval');           //用户ID
        $array_goods_num=I('post.array_goods_num',''); //商品货号组
        $array_shelf_row=I('post.array_shelf_row',''); //商品货号组对应列号
        $shelf_num      =I('post.shelf_num','');       //货架编号
        $putaway        =I('post.putaway','');         //是否上架 0下架  1上架
        $line           =I('post.in_row','');          //上架列数
        if($line==0&&$putaway==1){
            returnApiError("无法上架至0此列");
        }
        $goods_array = explode(",",$array_goods_num);
        if(count($goods_array)==0){
            returnApiError("商品货号组为空");
        }
        if(!empty($array_shelf_row)&&$putaway==0){
            $line_array = explode(",",$array_shelf_row);
            if(count($line_array)==0){
                returnApiError("商品货号对应列为空");
            }
            if(count($line_array)!=count($goods_array)){
                returnApiError("下架时，列号数与商品货号数数目不正确");
            }
        }

        $shelf_date = explode("-",$shelf_num);
        if(is_numeric($shelf_date[1])){
            //是货架与列的组合
            $shelf_num = $shelf_date[0];
            if(empty($line)){
                $line = $shelf_date[1];
            }
            //$in_row = $shelf_date[1];
        }





        $wid = $this->get_user_wid_identity($user_id);
        $shelves_data = M("shelves")->where(array("shelves_sn"=>$shelf_num,"state"=>1,"wid"=>$wid))->find();
        if(!$shelves_data){
            returnApiError("货架编码有误/已禁用");
        }
        if(empty($line)&&$putaway==1){
            returnApiError("所在列为空");
        }

        if($putaway==1){
            if($line>$shelves_data['s_floor']){
                returnApiError("超出最大货架列数");
            }
        }
        $shelves_goods_mod=M('shelves_goods');
        $goods_mod=M("goods");
        if($putaway==0){
            $i=0;
            $action_id=0;
            //下架时，不判断 直接下架
            foreach ($goods_array as $key=>$value){
                $count='';
                if(!empty($line_array[$key])){
                    $goods_data_one = $goods_mod->where(array("goods_sn"=>$value))->find();
                    $Results = $shelves_goods_mod->where("goods_sn = '".$value."' AND sh_id = '".$shelves_data['id']."' AND sh_floor = ".$line_array[$key])->delete();
                    if($Results){
                        if($i>0){
                            $this->w_action_log_goods($action_id,6,$goods_data_one['goods_name'],$value);
                        }else{
                            $action_id = $this->w_action_log_main($user_id,$shelves_data['id'],6,$line);
                            $this->w_action_log_goods($action_id,6,$goods_data_one['goods_name'],$value);
                        }
                        $count=$shelves_goods_mod->alias('sg')
                        ->join(C('DB_PREFIX').'shelves as s on sg.sh_id=s.id and s.wid='.$wid)
                        ->where(array("sg.goods_sn"=>$value))
                        ->count("sg.id");
                        if($count==0){
                            //根据商品货号修改该商品上下架状态，并且写入修改该商品上下架操作日志
                            //取消商品绑定货架管理
                            $this->update_goods_is_on_sale($value,0,$user_id,$wid);
                        }
                        $i++;
                        //exit(1);
                    }
                }else{
                    //returnApiError("");
                }


            }
            returnApiSuccess(null,"下架成功"+$count+"，一共下架：".$i);
        }else if($putaway==1){
            //上架商品，先判断在当前货架是否存在
            $is_in_s = false;
            $in_sn = null;
            $i=0;
            $action_id=0;
            foreach ($goods_array as $key=>$value){
                $where['goods_sn'] = $value;
                $where['sh_id'] = $shelves_data['id'];
                $where['sh_floor'] = $line;
                $is_in = $shelves_goods_mod->where($where)->count();
                if($is_in!=0){
                    //根据商品货号修改该商品上下架状态，并且写入修改该商品上下架操作日志
                    $this->update_goods_is_on_sale($value,1,$user_id,$wid);
                    $is_in =  true;
                    $is_in_s .=$value."\n";
                }
            }
            if(!empty($is_in)){
                //存在重复商品
                returnApiError("在此货架列上存在以下商品:\n".$is_in_s);
            }else{

                foreach ($goods_array as $key=>$value){
                    $shelves_goods_data['goods_sn'] = $value;
                    $shelves_goods_data['goods_id'] = M("goods")->where(array("goods_sn"=>$value))->getField("goods_id");
                    $shelves_goods_data['sh_id'] = $shelves_data['id'];
                    $shelves_goods_data['sh_floor'] = $line;
                    $shelves_goods_data['add_time'] = gmtime();
                    $shelves_goods_data['add_user'] = A("Distribution")->get_admin_user_name($user_id);
                    $Results = $shelves_goods_mod->add($shelves_goods_data);
                    //dump(M('shelves_goods')->getlastsql());
                    if($Results){
                        $goods_data_one = $goods_mod->where(array("goods_sn"=>$value))->find();
                        if($i>0){
                            $this->w_action_log_goods($action_id,5,$goods_data_one['goods_name'],$value);
                        }else{
                            $action_id = $this->w_action_log_main($user_id,$shelves_data['id'],5,$line);
                            $this->w_action_log_goods($action_id,5,$goods_data_one['goods_name'],$value);
                        }
                        //根据商品货号修改该商品上下架状态，并且写入修改该商品上下架操作日志
                        $this->update_goods_is_on_sale($value,1,$user_id,$wid);
                        $i++;
                        //exit(1);
                    }
                }
                returnApiSuccess(null,"一共上架:".$i);
            }
        }
    }


    /**
     * todo 写入货架记录
     * rui poptser@foxmail.com 2016-12-3 14:09:11
     * @param $user_id
     * @param $sh_id  货架ID
     * @param $type 操作类型 1 新建货架  2编辑货架 3启用货架 4禁用货架 5绑定商品 6解绑商品 7换绑商品
     * @param null $goods_name
     * @param null $goods_sn
     */
    public function w_action_log_main($user_id,$sh_id,$type,$s_floor=null){
        $distribute_info = A("Distribution")->get_admin_user_name($user_id);
        $data['user_id'] = $distribute_info['user_name']."( uid:".$user_id.")";
        $data['sh_id'] = $sh_id;
        $data['type'] = $type;
        $data['s_floor'] = $s_floor;
        $data['action_time'] = gmtime();
        $action_id = M('shelves_action')->add($data);
        return $action_id;
    }
    public function w_action_log_goods($action_id,$type,$goods_name,$goods_sn){
        if($type==5||$type==6||$type==7){
            $action_details['action_id'] = $action_id;
            $action_details['goods_sn'] = $goods_sn;
            $action_details['goods_name'] = $goods_name;
            $action_details['type'] = $type;
            M('shelves_action_details')->add($action_details);
        }else{
            //其他日志
        }
    }

    /*
     * 采购列表
     * 根据采购单号搜索采购单
     * */

    public function buy_list(){
        if(!$this->wprow){
            returnApiError("无此操作权限");
        }
        $keyword=trim(I('post.keyword'));
        $page=I('post.page','intval');
        $type=I('post.list_type');//0-未采购，1-未补齐，2-已补齐,3-采购取消,4-已结单
        $where['wpd.wid']=$this->wprow['wid'];
        if(!empty($keyword)){
            $where['wp.procurement_sn']=array('like','%'.$keyword.'%');
        }
        if($type!==''){
            if($type==1){
                $where['wpd.status']=array('in','0,1');
            }elseif ($type==0){
                $where['wpd.status']=array('in','2,3,4');
            }
        }
        $count=M('warehouse_procurement')->alias('wp')
            ->join(C('DB_PREFIX').'warehouse_procurement_detail as wpd on wp.id=wpd.procurement_id')
            ->join(C('DB_PREFIX').'warehouse_supplier as ws ON wp.supplier_id=ws.id')
            ->join(C('DB_PREFIX').'admin_user as au ON au.user_id=wp.add_userid')
            ->where($where)
            ->count('distinct wp.procurement_sn');
        $pagearr=show_page($count, $page,$this->pagesize);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }
        $list=M('warehouse_procurement')->alias('wp')
            ->field('wp.id as buy_id,wp.procurement_sn as buy_num,wp.supplier_id,wp.add_userid,wp.add_time as create_time,wpd.status,ws.name as provider,au.ture_name as create_user,wpd.production_date')
            ->join(C('DB_PREFIX').'warehouse_procurement_detail as wpd on wp.id=wpd.procurement_id')
            ->join(C('DB_PREFIX').'warehouse_supplier as ws ON wp.supplier_id=ws.id')
            ->join(C('DB_PREFIX').'admin_user as au ON au.user_id=wp.add_userid')
            ->where($where)
            ->order('wp.id desc,wp.add_time desc')
            ->group('wp.procurement_sn')
            ->limit($pagearr['firstpage'].','.$this->pagesize)
            ->select();
        if($list){
            $warehouse_procurement_detail_mod=M('warehouse_procurement_detail');
            foreach ($list as $k=>$v){
                $list[$k]['create_time']=local_date('Y-m-d H:i:s',$v['create_time']);
                $list[$k]['buy_state']=$this->get_procurement_status($v['status']);
                $buy_goods_type=$warehouse_procurement_detail_mod->where(array('procurement_id'=>$v['buy_id']))->count();
                $list[$k]['buy_goods_type']=$buy_goods_type;
                if($v['production_date']==0){
                    $list[$k]['start_date']='';
                }else{
                    $list[$k]['start_date']=date('Y-m-d',$v['production_date']);
                }
            }
            returnApiSuccess(array('list'=>$list,'is_last'=>$is_last),'success');
        }else{
            returnApiSuccess(array('list'=>array(),'is_last'=>1),'没有数据');
        }
    }

    private function get_procurement_status($status){
        $status_name='';
        if($status==0){
            $status_name='未采购';
        }elseif($status==1){
            $status_name='未补齐';
        }elseif($status==2){
            $status_name='已补齐';
        }elseif($status==3){
            $status_name='采购取消';
        }elseif($status==4){
            $status_name='已结单';
        }
        return $status_name;
    }

    private function get_goods_weight($val){
        if($val>0){
            if($val>=1){
                return $val.'/kg';
            }else{
                return ($val/ 0.001).'/g';
            }
        }
        return $val;

    }

    /*
     * //采购商品列表
     * 根据单个采购单查看采购商品列表
     * */
    public function buy_goods_list(){
        if(!$this->wprow){
            returnApiError("无此操作权限");
        }
        $procurement_id=I('post.buy_id','intval');
        if($procurement_id<=0){
            returnApiError("参数错误");
        }
        $page=I('post.page','intval');
        $where['wpd.procurement_id']=$procurement_id;
        $where['wpd.wid']=$this->wprow['wid'];
        $count=M('warehouse_procurement_detail')->alias('wpd')->where($where)
            ->join(C('DB_PREFIX').'warehouse_procurement as wp ON wp.id=wpd.procurement_id')
            ->join(C('DB_PREFIX').'goods as g ON g.goods_id=wpd.goods_id')
            ->count();
        $pagearr=show_page($count, $page,$this->pagesize);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }
        $list=M('warehouse_procurement_detail')->alias('wpd')->where($where)
            ->field('wpd.id as num_id,wp.id as buy_id,wp.procurement_sn as buy_num,g.goods_id,g.goods_sn as goods_num,g.goods_name,wpd.status,wpd.goods_weight,wpd.spec_value,wpd.spec_unit,wpd.order_box_gauge,wpd.tank_gauge_unit,wpd.goods_total_quantity,wpd.total_quantity,wpd.reality_acceptance_gauge,wpd.reality_acceptance_num,wpd.actual_inventory_quantity,wpd.in_actual_inventory_quantity,wpd.production_date')
            ->join(C('DB_PREFIX').'warehouse_procurement as wp ON wp.id=wpd.procurement_id')
            ->join(C('DB_PREFIX').'goods as g ON g.goods_id=wpd.goods_id')
            ->order('num_id desc')
            ->limit($pagearr['firstpage'].','.$this->pagesize)
            ->select();
        if($list){
            foreach ($list as $key=>$val){
                $sku=1;
                $list[$key]['buy_state']=$this->get_procurement_status($val['status']);
                $list[$key]['buy_info']=$val['order_box_gauge'].'('.$val['tank_gauge_unit'].')/'.$val['goods_total_quantity'].'箱/'.$val['total_quantity'].'(份)';
                $list[$key]['buyed_info']=$val['reality_acceptance_gauge'].'('.$val['tank_gauge_unit'].')/'.$val['reality_acceptance_num'].'箱/'.$val['actual_inventory_quantity'].'('.$val['total_quantity'].')';
                $total_quantity_old=$val['in_actual_inventory_quantity']-$val['actual_inventory_quantity'];
                if($total_quantity_old>0){
                    $list[$key]['remaining']=$total_quantity_old;
                }else{
                    $list[$key]['remaining']=0;
                }
                if(!empty($val['spec_value']) && count($val['spec_unit'])>0){
                    $sku=$val['spec_value'];
                }else{
                    $goods_weight=(float)$val['goods_weight'];
                    if($goods_weight){
                        if($goods_weight>=1){
                            $sku=$goods_weight;
                        }else{
                            $sku=$goods_weight/0.001;
                        }
                    }else{
                        unset($list[$key]);
                        continue;
                    }
                }
                if($val['production_date']==0){
                    $list[$key]['start_date']='';
                }else{
                    $list[$key]['start_date']=date('Y-m-d',$val['production_date']);
                }

                $list[$key]['sku']=$sku;
            }
            returnApiSuccess(array('list'=>$list,'is_last'=>$is_last),'success');
        }else{
            returnApiSuccess(array('list'=>array(),'is_last'=>1),'没有数据');
        }
    }

    //商品编号查询采购列表
    public function goods_num_query_buy_list(){
        if(!$this->wprow){
            returnApiError("无此操作权限");
        }
        $goods_sn=trim(I('post.goods_num'));
        if(empty($goods_sn)){
            returnApiError("商品编号不能为空");
        }
        $where['wpd.wid']=$this->wprow['wid'];
        $where['g.goods_sn']=array('like','%'.$goods_sn.'%');
        $where['_string']="((wpd.`status`=1 and wpd.reality_acceptance_gauge <> '' AND wpd.tank_gauge_unit <> '' AND wpd.in_actual_inventory_quantity <> '') or  wpd.`status`=0 )";
        $page=I('post.page','intval');
        $count=M('warehouse_procurement')->alias('wp')
            ->join(C('DB_PREFIX').'warehouse_procurement_detail as wpd on wp.id=wpd.procurement_id')
            ->join(C('DB_PREFIX').'warehouse_supplier as ws ON wp.supplier_id=ws.id')
            ->join(C('DB_PREFIX').'admin_user as au ON au.user_id=wp.add_userid')
            ->join(C('DB_PREFIX').'goods as g ON g.goods_id=wpd.goods_id')
            ->where($where)
            ->count('distinct wp.procurement_sn');
        $pagearr=show_page($count, $page,$this->pagesize);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }
        $list=M('warehouse_procurement')->alias('wp')
            ->field('wp.id as buy_id,wp.procurement_sn as buy_num,wp.supplier_id,wp.add_userid,wp.add_time as create_time,wpd.status,ws.name as provider,au.ture_name as create_user')
            ->join(C('DB_PREFIX').'warehouse_procurement_detail as wpd on wp.id=wpd.procurement_id')
            ->join(C('DB_PREFIX').'warehouse_supplier as ws ON wp.supplier_id=ws.id')
            ->join(C('DB_PREFIX').'admin_user as au ON au.user_id=wp.add_userid')
            ->join(C('DB_PREFIX').'goods as g ON g.goods_id=wpd.goods_id')
            ->where($where)
            ->order('wp.id desc,wp.add_time desc')
            ->group('wp.procurement_sn')
            ->limit($pagearr['firstpage'].','.$this->pagesize)
            ->select();
        if($list){
            $warehouse_procurement_detail_mod=M('warehouse_procurement_detail');
            foreach ($list as $k=>$v){
                $list[$k]['create_time']=local_date('Y-m-d H:i:s',$v['create_time']);
                $list[$k]['buy_state']=$this->get_procurement_status($v['status']);
                $buy_goods_list=$warehouse_procurement_detail_mod->alias('wpd')
                    ->join(C('DB_PREFIX').'goods as g ON g.goods_id=wpd.goods_id')
                    ->where(array('wpd.procurement_id'=>$v['buy_id']))
                    ->field('g.goods_id,g.goods_sn as goods_num,g.goods_name,wpd.status,wpd.order_box_gauge,wpd.tank_gauge_unit,wpd.goods_total_quantity,wpd.total_quantity,wpd.reality_acceptance_gauge,wpd.reality_acceptance_num,wpd.actual_inventory_quantity,wpd.production_date')
                    ->select();
                if($buy_goods_list){
                    foreach ($buy_goods_list as $key=>$val){
                        $buy_goods_list[$key]['buy_state']=$this->get_procurement_status($val['status']);
                        $buy_goods_list[$key]['buy_info']=$val['order_box_gauge'].'('.$val['tank_gauge_unit'].')/'.$val['goods_total_quantity'].'箱/'.$val['total_quantity'].'(份)';
                        $buy_goods_list[$key]['buyed_info']=$val['reality_acceptance_gauge'].'('.$val['tank_gauge_unit'].')/'.$val['reality_acceptance_num'].'箱/'.$val['actual_inventory_quantity'].'('.$val['total_quantity'].')';
                        if($val['production_date']==0){
                            $buy_goods_list[$key]['start_date']='';
                        }else{
                            $buy_goods_list[$key]['start_date']=$val['production_date'];
                        }
                    }
                }
                $list[$k]['buy_goods_list']=$buy_goods_list;
            }
            returnApiSuccess(array('list'=>$list,'is_last'=>$is_last),'success');
        }else{
            returnApiSuccess(array('list'=>array(),'is_last'=>1),'没有数据');
        }
    }

    //商品入库
    public function goods_buyed(){
        if(!$this->wprow){
            returnApiError("无此操作权限");
        }
        $procurement_id=I('post.buy_id','intval');
        $wpd_id=I('post.num_id','intval');
        $goods_id=I('post.goods_id','intval');
        $reality_acceptance_gauge=I('post.buy_unit','intval');
        $reality_acceptance_num=I('post.buy_unit_count','intval');
        $actual_inventory_quantity=I('post.buy_real_count','intval');
        $in_actual_inventory_quantity=I('post.buy_putin_count','intval');
        $start_date=I('post.start_date');
        $remainder=I('post.remainder');
        if($procurement_id<=0 || $wpd_id<=0 || $goods_id<=0  || $in_actual_inventory_quantity<=0){
            returnApiError("参数错误");
        }

        $wid=$this->wprow['wid'];
        $user_id=$this->wprow['uid'];
        $wplist=M('warehouse_procurement')->alias('wp')
            ->field('wp.id,wpd.id as num_id,wp.procurement_sn,wpd.goods_id,wpd.goods_sn,wpd.goods_name,wpd.actual_inventory_quantity,wpd.goods_total_quantity,wpd.total_quantity,wpd.reality_acceptance_gauge,wpd.reality_acceptance_num,wpd.in_actual_inventory_quantity,wpd.production_date')
            ->join(C('DB_PREFIX').'warehouse_procurement_detail as wpd on wp.id=wpd.procurement_id')
            ->where(array('wpd.id'=>$wpd_id,'wpd.procurement_id'=>$procurement_id,'wpd.wid'=>$wid))
            ->find();
        if(!$wplist){
            returnApiError("查无此采购单商品！");
        }
        if(empty($start_date)){
            $start_date=$wplist['production_date'];
        }else{
            $start_date=strtotime($start_date);
            if($start_date===false){
                $start_date=0;
            }
        }
        $gs_mod=M('goods_storage');
        $wpd_mod=M('warehouse_procurement_detail');
        //检查对应仓库中是否有该商品，若有则直接修改库存，若没有，新增新的商品入库
        $goods_storagelist=$gs_mod->where(array('wid'=>$wid,'goods_id'=>$goods_id))->find();

        if($goods_storagelist){
            //获取实际库存缓存
            $cache_goods_practical_num = get_goods_practical_num_cache($goods_id,$wid,$goods_storagelist['practical_num']);
            //获取队列库存缓存
            $cache_queue_goods_stock = get_queue_goods_stock($goods_id,$wid);
            $data=array(
                'practical_num'=>$goods_storagelist['practical_num']+$actual_inventory_quantity,
            );
            $gsid=$gs_mod->where(array('wid'=>$wid,'goods_id'=>$goods_id))->save($data);
            if($gsid!==false){
                //更新实际库存缓存
                set_goods_practical_num_cache($goods_id,$wid,$cache_goods_practical_num+$actual_inventory_quantity);
                //更新队列库存缓存
                set_queue_goods_stock($goods_id,$wid,$cache_queue_goods_stock+$actual_inventory_quantity);
                $gsrdata=array(
                    'goods_storage_id'=>$goods_storagelist['id'],
                    'wpid'=>$procurement_id,
                    'goods_id'=>$goods_storagelist['goods_id'],
                    'goods_sn'=>$goods_storagelist['goods_sn'],
                    'operation_num'=>$actual_inventory_quantity,
                    'real_num'=>$goods_storagelist['practical_num']+$actual_inventory_quantity,
                    'frozen_num'=>0,
                    'defective_num'=>0,
                    'operation_userid'=>$user_id,
                    'operation_addtime'=>gmtime(),
                    'source_no'=>$wplist['procurement_sn'],
                    'record_type'=>1,
                    'remark'=>''
                );
                //商品出入库记录
                M('goods_storage_record')->add($gsrdata);
                if($wplist['actual_inventory_quantity']>0 && !empty($wplist['reality_acceptance_gauge']) && !empty($wplist['reality_acceptance_num'])){
                    $sum=$wplist['in_actual_inventory_quantity']-($wplist['actual_inventory_quantity']+$actual_inventory_quantity);
                    if($sum<=0){
                        $status=2;
                    }else{
                        $status=1;
                    }
                    $data=array(
                        'actual_inventory_quantity'=>$wplist['actual_inventory_quantity']+$actual_inventory_quantity,
                        'status'=>$status,
                        'production_date'=>$start_date
                    );
                    $wpd_mod->where(array('id'=>$wplist['num_id']))->save($data);
                }else{
                    $sum=$in_actual_inventory_quantity-$actual_inventory_quantity;
                    if($sum<=0){
                        $status=2;
                    }else{
                        $status=1;
                    }
                    $data=array(
                        'actual_inventory_quantity'=>$actual_inventory_quantity,
                        'reality_acceptance_gauge'=>$reality_acceptance_gauge,
                        'reality_acceptance_num'=>$reality_acceptance_num,
                        'in_actual_inventory_quantity'=>$in_actual_inventory_quantity,
                        'remainder'=>$remainder,
                        'status'=>$status,
                        'production_date'=>$start_date
                    );
                    $wpd_mod->where(array('id'=>$wplist['num_id']))->save($data);
                }
                $og=array(
                    'wid'=>$wid,
                    'goods_id'=>$goods_storagelist['goods_id'],
                    'practical_num'=>$goods_storagelist['practical_num']+$actual_inventory_quantity,
                    'freeze_num'=>$goods_storagelist['freeze_num'],
                    'goods_storage_id'=>$goods_storagelist['id'],
                    'procurement_id'=>$wplist['id'],
                    'quantity_type'=>'仓管端采购入库',
                    'batch_no'=>$wplist['procurement_sn'],
                );
                //检查是否存在预售订单商品，若存在，进行实际库存操作
                $this->check_goods_order_quantity($og);
                returnApiSuccess(array('num_id'=>$wpd_id),'操作成功！');
            }else{
                returnApiError("采购商品入库出错");
            }
        }else{
            $data=array(
                'wid'=>$wid,
                'goods_id'=>$wplist['goods_id'],
                'goods_sn'=>$wplist['goods_sn'],
                'goods_name'=>$wplist['goods_name'],
                'practical_num'=>$actual_inventory_quantity,
                'freeze_num'=>0,
                'inferior_quality_num'=>0,
                'add_time'=>gmtime(),
            );
            $gsid=$gs_mod->add($data);
            if($gsid){
                //更新实际库存缓存
                set_goods_practical_num_cache($wplist['goods_id'],$wid,$actual_inventory_quantity);
                //更新队列库存缓存
                set_queue_goods_stock($wplist['goods_id'],$wid,$actual_inventory_quantity);
                $gsrdata=array(
                    'goods_storage_id'=>$gsid,
                    'wpid'=>$wplist['num_id'],
                    'goods_id'=>$wplist['goods_id'],
                    'goods_sn'=>$wplist['goods_sn'],
                    'operation_num'=>$actual_inventory_quantity,
                    'real_num'=>$actual_inventory_quantity,
                    'frozen_num'=>0,
                    'defective_num'=>0,
                    'operation_userid'=>$user_id,
                    'operation_addtime'=>gmtime(),
                    'source_no'=>$wplist['procurement_sn'],
                    'record_type'=>1,
                    'remark'=>''
                );
                $gsrid=M('goods_storage_record')->add($gsrdata);
                if($wplist['actual_inventory_quantity']>0 && !empty($wplist['reality_acceptance_gauge']) && !empty($wplist['reality_acceptance_num'])){
                    $sum=$wplist['in_actual_inventory_quantity']-($wplist['actual_inventory_quantity']+$actual_inventory_quantity);
                    if($sum<=0){
                        $status=2;
                    }else{
                        $status=1;
                    }
                    $data=array(
                        'actual_inventory_quantity'=>$wplist['actual_inventory_quantity']+$actual_inventory_quantity,
                        'status'=>$status,
                        'production_date'=>$start_date
                    );
                    $wpd_mod->where(array('id'=>$wplist['num_id']))->save($data);
                }else{
                    $sum=$in_actual_inventory_quantity-$actual_inventory_quantity;
                    if($sum<=0){
                        $status=2;
                    }else{
                        $status=1;
                    }
                    $data=array(
                        'actual_inventory_quantity'=>$actual_inventory_quantity,
                        'reality_acceptance_gauge'=>$reality_acceptance_gauge,
                        'reality_acceptance_num'=>$reality_acceptance_num,
                        'in_actual_inventory_quantity'=>$in_actual_inventory_quantity,
                        'remainder'=>$remainder,
                        'status'=>$status,
                        'production_date'=>$start_date
                    );
                    $wpd_mod->where(array('id'=>$wplist['num_id']))->save($data);
                }
                $og=array(
                    'wid'=>$wid,
                    'goods_id'=>$wplist['goods_id'],
                    'practical_num'=>$actual_inventory_quantity,
                    'freeze_num'=>0,
                    'goods_storage_id'=>$gsid,
                    'procurement_id'=>$wplist['id'],
                    'quantity_type'=>'仓库端采购入库',
                    'batch_no'=>$wplist['procurement_sn'],
                );
                //检查是否存在预售订单商品，若存在，进行实际库存操作
                $this->check_goods_order_quantity($og);
                returnApiSuccess(array('num_id'=>$wpd_id),'操作成功！');
            }else{

                returnApiError("采购添加商品入库出错");
            }
        }
    }

    /*
     * 采购完成
     * */

    public function buyed(){
        if(!$this->wprow){
            returnApiError("无此操作权限");
        }
        $procurement_id=I('post.buy_id','intval');
        if($procurement_id<=0){
            returnApiError("参数错误");
        }
        $wid=$this->wprow['wid'];
        M('warehouse_procurement_detail')->where(array('procurement_id'=>$procurement_id,'wid'=>$wid))->save(array('status'=>4));
        returnApiSuccess(array('id'=>$procurement_id),'操作成功！');
    }

    /*
     * 通过采购单里查询商品列表
     * 
     */
    public function goods_num_query_goods(){
        if(!$this->wprow){
            returnApiError("无此操作权限");
        }
        $procurement_id=I('post.buy_id','intval');
        $goods_sn=I('post.goods_num');
        if($procurement_id<=0 || empty($goods_sn)){
            returnApiError("参数错误");
        }
        $where['wpd.wid']=$this->wprow['wid'];
        $where['wpd.procurement_id']=$procurement_id;
        $where['g.goods_sn']=$goods_sn;
        $list=M('warehouse_procurement_detail')->alias('wpd')
            ->field('wp.id as buy_id,wpd.id as num_id,wp.procurement_sn as buy_num,g.goods_id,g.goods_sn as goods_num,g.goods_name,wpd.status,wpd.goods_weight,wpd.spec_value,wpd.spec_unit,wpd.order_box_gauge,wpd.tank_gauge_unit,wpd.goods_total_quantity,wpd.total_quantity,wpd.reality_acceptance_gauge,wpd.reality_acceptance_num,wpd.actual_inventory_quantity,wpd.in_actual_inventory_quantity,wpd.production_date')
            ->join(C('DB_PREFIX').'warehouse_procurement as wp ON wp.id=wpd.procurement_id')
            ->join(C('DB_PREFIX').'goods as g on g.goods_id=wpd.goods_id')
            ->where($where)
            ->select();
        if($list){
            foreach ($list as $key=>$val){
                $sku=1;
                $list[$key]['buy_state']=$this->get_procurement_status($val['status']);
                $list[$key]['buy_info']=$val['order_box_gauge'].'('.$val['tank_gauge_unit'].')/'.$val['goods_total_quantity'].'箱/'.$val['total_quantity'].'(份)';
                $list[$key]['buyed_info']=$val['reality_acceptance_gauge'].'('.$val['tank_gauge_unit'].')/'.$val['reality_acceptance_num'].'箱/'.$val['actual_inventory_quantity'].'('.$val['total_quantity'].')';
                $total_quantity_old=$val['in_actual_inventory_quantity']-$val['actual_inventory_quantity'];
                if($total_quantity_old>0){
                    $list[$key]['remaining']=$total_quantity_old;
                }else{
                    $list[$key]['remaining']=0;
                }
                if(!empty($val['spec_value']) && count($val['spec_unit'])>0){
                    $sku=$val['spec_value'];
                }else{
                    $goods_weight=(float)$val['goods_weight'];
                    if($goods_weight){
                        if($goods_weight>=1){
                            $sku=$goods_weight;
                        }else{
                            $sku=$goods_weight/0.001;
                        }
                    }else{
                        unset($list[$key]);
                        continue;
                    }
                }
                if($val['production_date']==0){
                    $list[$key]['start_date']='';
                }else{
                    $list[$key]['start_date']=$val['production_date'];
                }
                $list[$key]['sku']=$sku;
            }
            returnApiSuccess(array('list'=>$list),'success');
        }else{
            returnApiError('没有数据');
        }
    }

    /**
     * TODO 修改货架排序
     * rui poptser@foxmail.com 2017年2月5日14:50:31
     */
    public function shelf_list_edit(){
        $user_id=I('post.user_id','intval');            //用户ID
        $str_shelf=I('post.array_shelf_id','');       //货架ID组
        $array_shelf = explode(",",$str_shelf);
        if(count($array_shelf)==0){
            returnApiError("货架组为空");
        }

        $action_id = $this->w_sh_sort($user_id,$array_shelf[0],8);
        foreach ($array_shelf as $key=>$value){
            M("shelves")->where(array("id"=>$value))->setField('sort',$key+1);
            $action_details['action_id'] = $action_id;
            $action_details['sh_id'] = $value;
            $action_details['sort'] = $key+1;
            $action_details['type'] = 8;
            M("shelves_action_details")->add($action_details);
        }
        returnApiSuccess(null,"共处理完成.".$key."数据");
    }

    /*
     * 次品列表
     * */
    public function bad_list(){
        if(!$this->wprow){
            returnApiError("无此操作权限");
        }
        $page=I('post.page','intval');
        $where['bd.wid']=$this->wprow['wid'];
        $where['gs.inferior_quality_num']=array('gt',0);
        $where['g.is_delete']=0;
        $count=M('backflow_defectivegoods')->alias('bd')
            ->join(C('DB_PREFIX').'goods_storage as gs on gs.id=bd.goods_storage_id')
            ->join(C('DB_PREFIX').'goods as g on g.goods_id=bd.goods_id')
            ->where($where)
            ->count();
        $pagearr=show_page($count, $page,$this->pagesize);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }
        $backflow_defectivegoods_mod=M('backflow_defectivegoods');
        $list=$backflow_defectivegoods_mod->alias('bd')
            ->field('bd.id,bd.goods_id,g.goods_name,g.goods_sn as goods_num,bd.wid,bd.defectivegoods_num,gs.practical_num as store_count,gs.freeze_num,gs.inferior_quality_num')
            ->join(C('DB_PREFIX').'goods_storage as gs on gs.id=bd.goods_storage_id')
            ->join(C('DB_PREFIX').'goods as g on g.goods_id=bd.goods_id')
            ->where($where)
            ->order('bd.operation_addtime desc,bd.id desc')
            ->limit($pagearr['firstpage'].','.$this->pagesize)
            ->select();
        if($list){
            foreach ($list as $k=>$v){
                if($v['id']>0 && $v['inferior_quality_num']!=$v['defectivegoods_num']){
                    $backflow_defectivegoods_mod->where(array('id'=>$v['id'],'wid'=>$this->wprow['wid']))->save(array('defectivegoods_num'=>$v['inferior_quality_num']));
                }
                $dongjienum=$this->check_the_warehouse_record_goods($v['goods_id'],2);
                if($dongjienum>=0){
                    $list[$k]['dongjienum']=$dongjienum;
                    $list[$k]['store_count_bad']=$v['inferior_quality_num']-$dongjienum;
                    $list[$k]['inferior_quality_num']=$v['inferior_quality_num']-$dongjienum;
                    $list[$k]['defectivegoods_num']=$v['inferior_quality_num']-$dongjienum;
                }else{
                    $list[$k]['dongjienum']=0;
                    $list[$k]['store_count_bad']=0;
                }
                $list[$k]['source_warehouse']=$v['wid'];
                $wlist=$this->get_warehousename($v['wid']);
                $list[$k]['source_warehouse_name']=$wlist['name'];
            }
            returnApiSuccess(array('list'=>$list,'is_last'=>$is_last),'success');
        }else{
            returnApiSuccess(array('list'=>array(),'is_last'=>1),'没有数据');
        }
    }

    /*
     * 检查调仓记录中的商品是否调仓结束,若没有，那么就冻结对应操作数  -  调仓记录状态为1
     * */
    private function check_the_warehouse_record_goods($goods_id,$type){
        if(empty($goods_id) || empty($type)){
            return -1;
        }
        if($type==2){
            $where='(twr.the_warehouse_status in (1,2)) and twr.callout_wid='.$this->wprow['wid'].' and twgr.goods_id='.$goods_id.' and twr.the_warehousecause='.$type;
            $the_warehouse_num=M('the_warehouse_record')->alias('twr')
                ->field('IFNULL(SUM(twgr.the_warehouse_num),0) as the_warehouse_num_sum')
                ->join(C('DB_PREFIX').'the_warehouse_goods_record as twgr ON twgr.twid=twr.id')
                ->where($where)
                ->find();
            if($the_warehouse_num['the_warehouse_num_sum']==0){
                return 0;
            }else{
                return $the_warehouse_num['the_warehouse_num_sum'];
            }
        }else{
            return -1;
        }
    }

    /*
     * 单个商品操作
     * $type   1-次品录入   2-次品销毁  3-本仓回流  4-次品退货
     * */
    public function bad_handle(){
        if(!$this->wprow){
            returnApiError("无此操作权限");
        }
        $goods_id=I('post.goods_id','intval');
        $count=I('post.count','intval');
        $remark=I('post.remark');
        $type=I('post.type','intval');
        $img_file=$_FILES['img_file'];
        if($goods_id<=0 || $count<=0 || in_array($type, array(1,2,3,4))===false){
            returnApiError('参数错误');
        }
        if($img_file['size']>100){
            $path= "uploads/bad_handle/".rand(10000000,99999999).".".end(explode('.', $img_file['name']));//接收文件目录
            Ali_ossApi::upload($path, $img_file['tmp_name']);
        }
        
        $goods_storage_mod=M('goods_storage');
        $backflow_defectivegoods_mod=M('backflow_defectivegoods');
        $wid=$this->wprow['wid'];
        if($type==1){ //次品录入
            $gswhere=array('wid'=>$wid,'goods_id'=>$goods_id);
            $gsdata=$goods_storage_mod->where($gswhere)->find();
            if($gsdata){
                $batch_sn=$this->get_batch_sn('DPC');
                $cache_goods_practical_num=get_goods_practical_num_cache($goods_id, $wid, $gsdata['practical_num']);
                //获取队列库存缓存
                $cache_queue_goods_stock = get_queue_goods_stock($goods_id,$wid);
                if($gsdata['practical_num']>0 && $gsdata['practical_num']>=$count){
                    $bdwhere=array('wid'=>$wid,'goods_id'=>$goods_id);
                    //检查次品库中是否都存在该商品
                    $bdlist=$backflow_defectivegoods_mod->where($bdwhere)->find();
                    if($bdlist){
                        $bdsavedata=array('defectivegoods_num'=>$bdlist['defectivegoods_num']+$count,'operation_addtime'=>gmtime());
                        $bdid=$backflow_defectivegoods_mod->where($bdwhere)->save($bdsavedata);
                        //修改库存表中实际库存数据,次品数量+
                        $gssavedata=array('practical_num'=>$gsdata['practical_num']-$count,'inferior_quality_num'=>$gsdata['inferior_quality_num']+$count);
                        $gssave=$goods_storage_mod->where($gswhere)->save($gssavedata);
                        if($gssave!==false && $bdid!==false){
                            set_goods_practical_num_cache($goods_id, $wid, $cache_goods_practical_num-$count);
                            //更新队列库存缓存
                            set_queue_goods_stock($goods_id, $wid, $cache_queue_goods_stock-$count);
                            $gsrdata=array(
                                'goods_storage_id'=>$gsdata['id'],
                                'wpid'=>0,
                                'goods_id'=>$gsdata['goods_id'],
                                'goods_sn'=>$gsdata['goods_sn'],
                                'operation_num'=>$count,
                                'real_num'=>$gsdata['practical_num']-$count,
                                'frozen_num'=>0,
                                'defective_num'=>0,
                                'operation_userid'=>$this->wprow['uid'],
                                'operation_addtime'=>gmtime(),
                                'source_no'=>$batch_sn,
                                'record_type'=>5,
                                'remark'=>'次品录入'
                            );
                            //商品出入库记录
                            M('goods_storage_record')->add($gsrdata);
                            $bdfrdata=array(
                                'goods_storage_id'=>$gsdata['id'],
                                'bd_id'=>$bdlist['id'],
                                'wid'=>$gsdata['wid'],
                                'goods_id'=>$gsdata['goods_id'],
                                'goods_sn'=>$gsdata['goods_sn'],
                                'goods_name'=>$gsdata['goods_name'],
                                'freeze_num'=>$count,
                                'real_num'=>0,
                                'defective_num'=>$gsdata['inferior_quality_num']+$count,
                                'operation_userid'=>$this->wprow['uid'],
                                'operation_addtime'=>gmtime(),
                                'batch_no'=>$batch_sn,
                                'record_type'=>1,
                                'remark'=>$this->img_site.$path
                            );
                            M('backflow_defectivegoods_freeze_record')->add($bdfrdata);
                            $returndata=array(
                                'goods_id'=>$gsdata['goods_id'],
                                'goods_name'=>$gsdata['goods_name'],
                                'goods_num'=>$gsdata['goods_sn'],
                                'store_count'=>$gsdata['practical_num']-$count,
                                'store_count_bad'=>$gsdata['inferior_quality_num']+$count
                            );
                            returnApiSuccess(array('data'=>$returndata),'该商品次品录入成功！');
                        }else{
                            returnApiError('该商品次品录入操作失败');
                        }
                    }else{
                        $bddata=array(
                            'goods_storage_id'=>$gsdata['id'],
                            'wid'=>$gsdata['wid'],
                            'goods_id'=>$gsdata['goods_id'],
                            'goods_sn'=>$gsdata['goods_sn'],
                            'goods_name'=>$gsdata['goods_name'],
                            'defectivegoods_num'=>$count,
                            'operation_userid'=>$this->wprow['uid'],
                            'operation_addtime'=>gmtime(),
                            'backflow_documents_pic'=>$this->img_site.$path,
                            'documents_remark'=>$remark
                        );
                        //添加次品商品入库
                        $dbid=$backflow_defectivegoods_mod->add($bddata);
                        //修改库存表中实际库存数据,次品数量+
                        $gssavedata=array('practical_num'=>$gsdata['practical_num']-$count,'inferior_quality_num'=>$gsdata['inferior_quality_num']+$count);
                        $gssave=$goods_storage_mod->where($gswhere)->save($gssavedata);
                        if($dbid>0 && $gssave!==false){
                            $gsrdata=array(
                                'goods_storage_id'=>$gsdata['id'],
                                'wpid'=>0,
                                'goods_id'=>$gsdata['goods_id'],
                                'goods_sn'=>$gsdata['goods_sn'],
                                'operation_num'=>$count,
                                'real_num'=>$gsdata['practical_num']-$count,
                                'frozen_num'=>0,
                                'defective_num'=>0,
                                'operation_userid'=>$this->wprow['uid'],
                                'operation_addtime'=>gmtime(),
                                'source_no'=>$batch_sn,
                                'record_type'=>5,
                                'remark'=>'次品录入'
                            );
                            //商品出入库记录
                            M('goods_storage_record')->add($gsrdata);
                            $bdfrdata=array(
                                'goods_storage_id'=>$gsdata['id'],
                                'bd_id'=>$bdlist['id'],
                                'wid'=>$gsdata['wid'],
                                'goods_id'=>$gsdata['goods_id'],
                                'goods_sn'=>$gsdata['goods_sn'],
                                'goods_name'=>$gsdata['goods_name'],
                                'freeze_num'=>$count,
                                'real_num'=>0,
                                'defective_num'=>$gsdata['inferior_quality_num']+$count,
                                'operation_userid'=>$this->wprow['uid'],
                                'operation_addtime'=>gmtime(),
                                'batch_no'=>$batch_sn,
                                'record_type'=>1,
                                'remark'=>$this->img_site.$path
                            );
                            M('backflow_defectivegoods_freeze_record')->add($bdfrdata);
                            $returndata=array(
                                'goods_id'=>$gsdata['goods_id'],
                                'goods_name'=>$gsdata['goods_name'],
                                'goods_num'=>$gsdata['goods_sn'],
                                'store_count'=>$gsdata['practical_num']-$count,
                                'store_count_bad'=>$gsdata['inferior_quality_num']+$count
                            );
                            returnApiSuccess(array('data'=>$returndata),'该商品次品录入成功！');
                        }else{
                            returnApiError('该商品次品录入操作失败');
                        }
                    }
                }else{
                    returnApiError('该商品没有足够的实际库存');
                }
            }else{
                returnApiError('查无此商品');
            }
        }elseif ($type==2 || $type==4){  // 次品销毁
            $batch_sn=$this->get_batch_sn('XH');
            //查看该商品是否在次品冻结库里存在
            $bdlist=$backflow_defectivegoods_mod->where(array('wid'=>$wid,'goods_id'=>$goods_id))->find();
            $gslist=$goods_storage_mod->where(array('wid'=>$wid,'goods_id'=>$goods_id))->find();
            if($bdlist && $gslist){
                if($gslist['inferior_quality_num']>=$count){
                    //次品冻结库存次品数减，同时销毁数加
                    $bdid=$backflow_defectivegoods_mod->where(array('wid'=>$wid,'goods_id'=>$goods_id))->save(array('defectivegoods_num'=>$gslist['inferior_quality_num']-$count,'destruction_num'=>$bdlist['destruction_num']+$count,'operation_addtime'=>gmtime()));
                    $gsid=$goods_storage_mod->where(array('wid'=>$wid,'goods_id'=>$goods_id))->save(array('inferior_quality_num'=>$gslist['inferior_quality_num']-$count));
                    if($bdid && $gsid){
                        $bdfrdata=array(
                            'goods_storage_id'=>$gslist['id'],
                            'bd_id'=>$bdlist['id'],
                            'wid'=>$gslist['wid'],
                            'goods_id'=>$gslist['goods_id'],
                            'goods_sn'=>$gslist['goods_sn'],
                            'goods_name'=>$gslist['goods_name'],
                            'freeze_num'=>$count,
                            'real_num'=>0,
                            'defective_num'=>$gslist['inferior_quality_num']-$count,
                            'operation_userid'=>$this->wprow['uid'],
                            'operation_addtime'=>gmtime(),
                            'batch_no'=>$batch_sn
                        );
                        if($type==2){
                            $bdfrdata['record_type']=3;
                            $bdfrdata['remark']='次品销毁';
                        }elseif ($type==4){
                            $bdfrdata['record_type']=8;
                            $bdfrdata['remark']='次品退货';
                        }
                        //生成次品冻结记录
                        $bdfrid=M('backflow_defectivegoods_freeze_record')->add($bdfrdata);
                        $bddlist=M('backflow_defectivegoods_dispose')->where(array('wid'=>$bdlist['wid'],'batch_sn'=>$batch_sn))->find();
                        if($bddlist){
                            $batch_sn=$bddlist['batch_sn'];
                            $bddbdata=array(
                                'backflow_dispose_id'=>$bddlist['id'],
                                'batch_sn'=>$batch_sn,
                                'bd_id'=>$bdlist['id'],
                                'wid'=>$bdlist['wid'],
                                'goods_id'=>$gslist['goods_id'],
                                'goods_sn'=>$gslist['goods_sn'],
                                'goods_name'=>$gslist['goods_name'],
                                'backflow_num'=>$count,
                                'pending_num'=>$gslist['inferior_quality_num']-$count,
                                'destroyed_num'=>$count,
                                'butsales_num'=>0,
                                'add_time'=>gmtime(),
                            );
                            //生成次品处理批次商品
                            $bddbid=M('backflow_defectivegoods_dispose_batch')->add($bddbdata);
                            $returndata=array(
                                'goods_id'=>$gslist['goods_id'],
                                'goods_name'=>$gslist['goods_name'],
                                'goods_num'=>$gslist['goods_sn'],
                                'store_count'=>$gslist['practical_num'],
                                'store_count_bad'=>$gslist['inferior_quality_num']-$count
                            );
                            returnApiSuccess(array('data'=>$returndata),'该商品次品销毁成功！');
                        }else{
                            $bdddata=array(
                                'goods_storage_id'=>$bdlist['goods_storage_id'],
                                'batch_sn'=>$batch_sn,
                                'wid'=>$bdlist['wid'],
                                'operation_userid'=>$this->wprow['uid'],
                                'operation_addtime'=>gmtime(),
                                'backflow_documents_pic'=>$this->img_site.$path,
                                'documents_remark'=>$remark,
                                'status'=>2
                            );
                            //生成次品处理记录
                            $bddid=M('backflow_defectivegoods_dispose')->add($bdddata);
                            if($bddid){
                                $bddbdata=array(
                                    'backflow_dispose_id'=>$bddid,
                                    'batch_sn'=>$batch_sn,
                                    'bd_id'=>$bdlist['id'],
                                    'wid'=>$bdlist['wid'],
                                    'goods_id'=>$gslist['goods_id'],
                                    'goods_sn'=>$gslist['goods_sn'],
                                    'goods_name'=>$gslist['goods_name'],
                                    'backflow_num'=>$count,
                                    'pending_num'=>$gslist['inferior_quality_num']-$count,
                                    'destroyed_num'=>$count,
                                    'butsales_num'=>0,
                                    'add_time'=>gmtime(),
                                );
                                //生成次品处理批次商品
                                $bddbid=M('backflow_defectivegoods_dispose_batch')->add($bddbdata);
                                $returndata=array(
                                    'goods_id'=>$gslist['goods_id'],
                                    'goods_name'=>$gslist['goods_name'],
                                    'goods_num'=>$gslist['goods_sn'],
                                    'store_count'=>$gslist['practical_num'],
                                    'store_count_bad'=>$gslist['inferior_quality_num']-$count
                                );
                                returnApiSuccess(array('data'=>$returndata),'该商品次品销毁成功！');
                            }
                        }
                    }else{
                        returnApiError('该操作次品销毁失败');
                    }
                }else{
                    returnApiError('该商品没有足够的次品');
                }
            }else{
                returnApiError('查无此商品');
            }
        }elseif ($type==3){//本仓回流
            $batch_sn=$this->get_batch_sn('HL');
            //查看该商品是否在次品冻结库里存在
            $bdlist=$backflow_defectivegoods_mod->where(array('wid'=>$wid,'goods_id'=>$goods_id))->find();
            $gslist=$goods_storage_mod->where(array('wid'=>$wid,'goods_id'=>$goods_id))->find();
            if($bdlist && $gslist){
                $cache_goods_practical_num=get_goods_practical_num_cache($goods_id, $wid, $gslist['practical_num']);
                //获取队列库存缓存
                $cache_queue_goods_stock = get_queue_goods_stock($goods_id, $wid);
                //次品冻结库存次品数减，同时回流数加
                if($count>$gslist['inferior_quality_num']){
                    returnApiError('该商品没有足够的次品');
                }
                $bdid=$backflow_defectivegoods_mod->where(array('wid'=>$wid,'goods_id'=>$goods_id))->save(array('defectivegoods_num'=>$gslist['inferior_quality_num']-$count,'recycled_num'=>$bdlist['recycled_num']+$count,'operation_addtime'=>gmtime()));
                $gsid=$goods_storage_mod->where(array('wid'=>$wid,'goods_id'=>$goods_id))->save(array('practical_num'=>$gslist['practical_num']+$count,'inferior_quality_num'=>$gslist['inferior_quality_num']-$count));
                if($bdid!==false && $gsid!==false){
                    set_goods_practical_num_cache($goods_id, $wid, $cache_goods_practical_num+$count);
                    //更新队列库存缓存
                    set_queue_goods_stock($goods_id, $wid, $cache_queue_goods_stock+$count);
                    $bdfrdata=array(
                        'goods_storage_id'=>$gslist['id'],
                        'bd_id'=>$bdlist['id'],
                        'wid'=>$gslist['wid'],
                        'goods_id'=>$gslist['goods_id'],
                        'goods_sn'=>$gslist['goods_sn'],
                        'goods_name'=>$gslist['goods_name'],
                        'freeze_num'=>$count,
                        'real_num'=>0,
                        'defective_num'=>$gslist['inferior_quality_num']-$count,
                        'operation_userid'=>$this->wprow['uid'],
                        'operation_addtime'=>gmtime(),
                        'batch_no'=>$batch_sn,
                        'record_type'=>4,
                        'remark'=>'重新销售'
                    );
                    //生成次品冻结记录
                    $bdfrid=M('backflow_defectivegoods_freeze_record')->add($bdfrdata);
                    $gsrdata=array(
                        'goods_storage_id'=>$gslist['id'],
                        'wpid'=>0,
                        'goods_id'=>$gslist['goods_id'],
                        'goods_sn'=>$gslist['goods_sn'],
                        'operation_num'=>$count,
                        'real_num'=>$gslist['practical_num']+$count,
                        'frozen_num'=>0,
                        'defective_num'=>0,
                        'operation_userid'=>$this->wprow['uid'],
                        'operation_addtime'=>gmtime(),
                        'source_no'=>$batch_sn,
                        'record_type'=>9,
                        'remark'=>'重新销售'
                    );
                    $gsrid=M('goods_storage_record')->add($gsrdata);
                    if($bdfrid){
                        $bddlist=M('backflow_defectivegoods_dispose')->where(array('wid'=>$bdlist['wid'],'batch_sn'=>$batch_sn))->find();
                        if($bddlist){
                            $batch_sn=$bddlist['batch_sn'];
                            $bddbdata=array(
                                'backflow_dispose_id'=>$bddlist['id'],
                                'batch_sn'=>$batch_sn,
                                'bd_id'=>$bdlist['id'],
                                'wid'=>$bdlist['wid'],
                                'goods_id'=>$gslist['goods_id'],
                                'goods_sn'=>$gslist['goods_sn'],
                                'goods_name'=>$gslist['goods_name'],
                                'backflow_num'=>$count,
                                'pending_num'=>$gslist['inferior_quality_num']-$count,
                                'destroyed_num'=>0,
                                'butsales_num'=>$count,
                                'add_time'=>gmtime(),
                            );
                            //生成次品处理批次商品
                            $bddbid=M('backflow_defectivegoods_dispose_batch')->add($bddbdata);
                        }else{
                            $bdddata=array(
                                'goods_storage_id'=>$bdlist['goods_storage_id'],
                                'batch_sn'=>$batch_sn,
                                'wid'=>$bdlist['wid'],
                                'operation_userid'=>$this->wprow['uid'],
                                'operation_addtime'=>gmtime(),
                                'backflow_documents_pic'=>$this->img_site.$path,
                                'documents_remark'=>$remark,
                                'status'=>2
                            );
                            //生成次品处理记录
                            $bddid=M('backflow_defectivegoods_dispose')->add($bdddata);
                            if($bddid){
                                $bddbdata=array(
                                    'backflow_dispose_id'=>$bddid,
                                    'batch_sn'=>$batch_sn,
                                    'bd_id'=>$bdlist['id'],
                                    'wid'=>$bdlist['wid'],
                                    'goods_id'=>$gslist['goods_id'],
                                    'goods_sn'=>$gslist['goods_sn'],
                                    'goods_name'=>$gslist['goods_name'],
                                    'backflow_num'=>$count,
                                    'pending_num'=>$gslist['inferior_quality_num']-$count,
                                    'destroyed_num'=>0,
                                    'butsales_num'=>$count,
                                    'add_time'=>gmtime(),
                                );
                                //生成次品处理批次商品
                                $bddbid=M('backflow_defectivegoods_dispose_batch')->add($bddbdata);
                            }
                        }
                    }
                    $returndata=array(
                        'goods_id'=>$gslist['goods_id'],
                        'goods_name'=>$gslist['goods_name'],
                        'goods_num'=>$gslist['goods_sn'],
                        'store_count'=>$gslist['practical_num']+$count,
                        'store_count_bad'=>$gslist['inferior_quality_num']-$count
                    );
                    returnApiSuccess(array('data'=>$returndata),'该商品次品销毁成功！');
                }else{
                    returnApiError('该操作次品回流失败');
                }
            }else{
                returnApiError('查无此商品');
            }
        }


    }

    /*
     * 获取指定次品列表
     * */

    public function bad_list_with_goods_num(){
        if(!$this->wprow){
            returnApiError("无此操作权限");
        }
        $list_goods_num=I('post.list_goods_num');
        $list_goods=json_decode(htmlspecialchars_decode($list_goods_num));
        $type=I('post.type','intval');
        if(empty($list_goods_num) || !is_array($list_goods) || in_array($type, array(1,2,3))===false){
            returnApiError('参数错误');
        }
        $goods_sn_arr=implode(',',$list_goods);
        if($type==1){
            $where['gs.wid']=$this->wprow['wid'];
            $where['g.goods_sn']=array('in',$goods_sn_arr);
            $where['g.is_delete']=0;
            $list=M('goods_storage')->alias('gs')
                ->field('g.goods_id,g.goods_name,g.goods_sn as goods_num,gs.practical_num as store_count,gs.inferior_quality_num as store_count_bad')
                ->join(C('DB_PREFIX').'goods as g on g.goods_id=gs.goods_id')
                ->where($where)
                ->order('gs.id desc')
                ->select();
            if($list){
                returnApiSuccess(array('list'=>$list),'success');
            }else{
                returnApiSuccess(array('list'=>array()),'没有数据');
            }
        }elseif($type==2 || $type==3){
            $where['bd.wid']=$this->wprow['wid'];
            $where['g.goods_sn']=array('in',$goods_sn_arr);
            $where['g.is_delete']=0;
            $backflow_defectivegoods_mod=M('backflow_defectivegoods');
            $list=$backflow_defectivegoods_mod->alias('bd')
                ->field('bd.id,bd.goods_id,g.goods_name,g.goods_sn as goods_num,bd.wid,bd.defectivegoods_num,gs.practical_num as store_count,gs.freeze_num,gs.inferior_quality_num')
                ->join(C('DB_PREFIX').'goods_storage as gs on gs.id=bd.goods_storage_id')
                ->join(C('DB_PREFIX').'goods as g on g.goods_id=bd.goods_id')
                ->where($where)
                ->order('bd.operation_addtime desc,bd.id desc')
                ->select();
            if($list){
                foreach ($list as $k=>$v){
                    if($v['id']>0 && $v['inferior_quality_num']!=$v['defectivegoods_num']){
                        $backflow_defectivegoods_mod->where(array('id'=>$v['id'],'wid'=>$this->wprow['wid']))->save(array('defectivegoods_num'=>$v['inferior_quality_num']));
                    }
                    $dongjienum=$this->check_the_warehouse_record_goods($v['goods_id'],2);
                    if($dongjienum>=0){
                        $list[$k]['dongjienum']=$dongjienum;
                        $list[$k]['store_count_bad']=$v['inferior_quality_num']-$dongjienum;
                    }else{
                        $list[$k]['dongjienum']=0;
                        $list[$k]['store_count_bad']=0;
                    }
                    $list[$k]['source_warehouse']=$v['wid'];
                    $wlist=$this->get_warehousename($v['wid']);
                    $list[$k]['source_warehouse_name']=$wlist['name'];
                }
                returnApiSuccess(array('list'=>$list),'success');
            }else{
                returnApiSuccess(array('list'=>array()),'没有数据');
            }
        }

    }

    /*
     * 商品批量操作
     * $type   1-次品录入   2-次品销毁 3-本仓回流
     * */
    public function bads_handle(){
        if(!$this->wprow){
            returnApiError("无此操作权限");
        }
        $list_bad_handle=json_decode(htmlspecialchars_decode(I('post.list_bad_handle')));
        $remark=I('post.remark');
        $img_file=$_FILES['img_file'];
        $type=I('post.type','intval');
        $list_bad=$this->objarray_to_array($list_bad_handle);
        if(empty($list_bad_handle) || !is_array($list_bad) || in_array($type, array(1,2,3,4))===false){
            returnApiError('参数错误');
        }
        if($img_file['size']>100){
            $path= "uploads/bads_handle/".rand(10000000,99999999).".".end(explode('.', $img_file['name']));//接收文件目录
            Ali_ossApi::upload($path, $img_file['tmp_name']);
        }
        $goods_storage_mod=M('goods_storage');
        $backflow_defectivegoods_mod=M('backflow_defectivegoods');
        $wid=$this->wprow['wid'];
        if($type==1){
            $batch_sn=$this->get_batch_sn('DPC');
        }elseif ($type==2 || $type==4){
            $batch_sn=$this->get_batch_sn('XH');
        }elseif($type==3){
            $batch_sn=$this->get_batch_sn('HL');
        }
        $data_return=$data_return1=array();
        foreach ($list_bad as $k=>$v){
            $goods_id=intval($v['goods_id']);
            $count=intval($v['count']);
            $goods_sn=$v['goods_num'];
            if($type==1){ //次品录入
                $gswhere=array('wid'=>$wid,'goods_id'=>$goods_id);
                $gsdata=$goods_storage_mod->where($gswhere)->find();
                if($gsdata){
                    if($count<=0){
                        $data_return[]=array(
                            'goods_id'=>$goods_id,
                            'goods_name'=>$gsdata['goods_name'],
                            'goods_num'=>$goods_sn,
                            'store_count'=>$gsdata['practical_num'],
                            'store_count_bad'=>$gsdata['inferior_quality_num'],
                            'err_msg'=>'该商品操作数请输入大于0的正整数',
                        );
                        continue;
                    }
                    $cache_goods_practical_num=get_goods_practical_num_cache($goods_id, $wid, $gsdata['practical_num']);
                    //获取队列库存缓存
                    $cache_queue_goods_stock = get_queue_goods_stock($goods_id, $wid);
                    if($gsdata['practical_num']>0 && $gsdata['practical_num']>=$count){
                        $bdwhere=array('wid'=>$wid,'goods_id'=>$goods_id);
                        //检查次品库中是否都存在该商品
                        $bdlist=$backflow_defectivegoods_mod->where($bdwhere)->find();
                        if($bdlist){
                            $bdsavedata=array('defectivegoods_num'=>$bdlist['defectivegoods_num']+$count,'operation_addtime'=>gmtime());
                            $bdid=$backflow_defectivegoods_mod->where($bdwhere)->save($bdsavedata);
                            //修改库存表中实际库存数据,次品数量+
                            $gssavedata=array('practical_num'=>$gsdata['practical_num']-$count,'inferior_quality_num'=>$gsdata['inferior_quality_num']+$count);
                            $gssave=$goods_storage_mod->where($gswhere)->save($gssavedata);
                            if($gssave!==false && $bdid!==false){
                                set_goods_practical_num_cache($goods_id, $wid, $cache_goods_practical_num-$count);
                                //更新队列库存缓存
                                set_queue_goods_stock($goods_id, $wid, $cache_queue_goods_stock-$count);
                                $gsrdata=array(
                                    'goods_storage_id'=>$gsdata['id'],
                                    'wpid'=>0,
                                    'goods_id'=>$gsdata['goods_id'],
                                    'goods_sn'=>$gsdata['goods_sn'],
                                    'operation_num'=>$count,
                                    'real_num'=>$gsdata['practical_num']-$count,
                                    'frozen_num'=>0,
                                    'defective_num'=>0,
                                    'operation_userid'=>$this->wprow['uid'],
                                    'operation_addtime'=>gmtime(),
                                    'source_no'=>$batch_sn,
                                    'record_type'=>5,
                                    'remark'=>'次品录入'
                                );
                                //商品出入库记录
                                M('goods_storage_record')->add($gsrdata);
                                $bdfrdata=array(
                                    'goods_storage_id'=>$gsdata['id'],
                                    'bd_id'=>$bdlist['id'],
                                    'wid'=>$gsdata['wid'],
                                    'goods_id'=>$gsdata['goods_id'],
                                    'goods_sn'=>$gsdata['goods_sn'],
                                    'goods_name'=>$gsdata['goods_name'],
                                    'freeze_num'=>$count,
                                    'real_num'=>0,
                                    'defective_num'=>$gsdata['inferior_quality_num']+$count,
                                    'operation_userid'=>$this->wprow['uid'],
                                    'operation_addtime'=>gmtime(),
                                    'batch_no'=>$batch_sn,
                                    'record_type'=>1,
                                    'remark'=>$this->img_site.$path
                                );
                                M('backflow_defectivegoods_freeze_record')->add($bdfrdata);
                            }else{
                                $data_return[]=array(
                                    'goods_id'=>$gsdata['goods_id'],
                                    'goods_name'=>$gsdata['goods_name'],
                                    'goods_num'=>$gsdata['goods_sn'],
                                    'store_count'=>$gsdata['practical_num'],
                                    'store_count_bad'=>$gsdata['inferior_quality_num'],
                                    'err_msg'=>'该商品次品录入操作失败',
                                );
                            }
                        }else{
                            $bddata=array(
                                'goods_storage_id'=>$gsdata['id'],
                                'wid'=>$gsdata['wid'],
                                'goods_id'=>$gsdata['goods_id'],
                                'goods_sn'=>$gsdata['goods_sn'],
                                'goods_name'=>$gsdata['goods_name'],
                                'defectivegoods_num'=>$count,
                                'operation_userid'=>$this->wprow['uid'],
                                'operation_addtime'=>gmtime(),
                                'backflow_documents_pic'=>$this->img_site.$path,
                                'documents_remark'=>$remark
                            );
                            //添加次品商品入库
                            $dbid=$backflow_defectivegoods_mod->add($bddata);
                            //修改库存表中实际库存数据,次品数量+
                            $gssavedata=array('practical_num'=>$gsdata['practical_num']-$count,'inferior_quality_num'=>$gsdata['inferior_quality_num']+$count);
                            $gssave=$goods_storage_mod->where($gswhere)->save($gssavedata);
                            if($dbid>0 && $gssave!==false){
                                set_goods_practical_num_cache($goods_id, $wid, $cache_goods_practical_num-$count);
                                //更新队列库存缓存
                                set_queue_goods_stock($goods_id, $wid, $cache_queue_goods_stock-$count);
                                $gsrdata=array(
                                    'goods_storage_id'=>$gsdata['id'],
                                    'wpid'=>0,
                                    'goods_id'=>$gsdata['goods_id'],
                                    'goods_sn'=>$gsdata['goods_sn'],
                                    'operation_num'=>$count,
                                    'real_num'=>$gsdata['practical_num']-$count,
                                    'frozen_num'=>0,
                                    'defective_num'=>0,
                                    'operation_userid'=>$this->wprow['uid'],
                                    'operation_addtime'=>gmtime(),
                                    'source_no'=>$batch_sn,
                                    'record_type'=>5,
                                    'remark'=>'次品录入'
                                );
                                //商品出入库记录
                                M('goods_storage_record')->add($gsrdata);
                                $bdfrdata=array(
                                    'goods_storage_id'=>$gsdata['id'],
                                    'bd_id'=>$dbid,
                                    'wid'=>$gsdata['wid'],
                                    'goods_id'=>$gsdata['goods_id'],
                                    'goods_sn'=>$gsdata['goods_sn'],
                                    'goods_name'=>$gsdata['goods_name'],
                                    'freeze_num'=>$count,
                                    'real_num'=>0,
                                    'defective_num'=>$gsdata['inferior_quality_num']+$count,
                                    'operation_userid'=>$this->wprow['uid'],
                                    'operation_addtime'=>gmtime(),
                                    'batch_no'=>$batch_sn,
                                    'record_type'=>1,
                                    'remark'=>$this->img_site.$path
                                );
                                M('backflow_defectivegoods_freeze_record')->add($bdfrdata);
                            }else{
                                $data_return[]=array(
                                    'goods_id'=>$gsdata['goods_id'],
                                    'goods_name'=>$gsdata['goods_name'],
                                    'goods_num'=>$gsdata['goods_sn'],
                                    'store_count'=>$gsdata['practical_num'],
                                    'store_count_bad'=>$gsdata['inferior_quality_num'],
                                    'err_msg'=>'该商品次品录入操作失败',
                                );
                            }
                        }
                    }else{
                        $data_return[]=array(
                            'goods_id'=>$gsdata['goods_id'],
                            'goods_name'=>$gsdata['goods_name'],
                            'goods_num'=>$gsdata['goods_sn'],
                            'store_count'=>$gsdata['practical_num'],
                            'store_count_bad'=>$gsdata['inferior_quality_num'],
                            'err_msg'=>'该商品没有足够的实际库存',
                        );
                    }
                }else{
                    $data_return[]=array(
                        'goods_id'=>$goods_id,
                        'goods_name'=>'',
                        'goods_num'=>$goods_sn,
                        'store_count'=>0,
                        'store_count_bad'=>0,
                        'err_msg'=>'查无此商品',
                    );
                }
            }elseif ($type==2 || $type==4){ //次品销毁
                //查看该商品是否在次品冻结库里存在
                $bdlist=$backflow_defectivegoods_mod->where(array('wid'=>$wid,'goods_id'=>$goods_id))->find();
                $gslist=$goods_storage_mod->where(array('wid'=>$wid,'goods_id'=>$goods_id))->find();
                if($bdlist && $gslist){
                    if($count<=0){
                        $data_return[]=array(
                            'goods_id'=>$goods_id,
                            'goods_name'=>$gslist['goods_name'],
                            'goods_num'=>$goods_sn,
                            'store_count'=>$gslist['practical_num'],
                            'store_count_bad'=>$gslist['inferior_quality_num'],
                            'err_msg'=>'该商品操作数请输入大于0的正整数',
                        );
                        continue;
                    }
                    if($gslist['inferior_quality_num']>=$count){
                        //次品冻结库存次品数减，同时销毁数加
                        $bdid=$backflow_defectivegoods_mod->where(array('wid'=>$wid,'goods_id'=>$goods_id))->save(array('defectivegoods_num'=>$gslist['inferior_quality_num']-$count,'destruction_num'=>$bdlist['destruction_num']+$count,'operation_addtime'=>gmtime()));
                        $gsid=$goods_storage_mod->where(array('wid'=>$wid,'goods_id'=>$goods_id))->save(array('inferior_quality_num'=>$gslist['inferior_quality_num']-$count));
                        if($bdid && $gsid){
                            $bdfrdata=array(
                                'goods_storage_id'=>$gslist['id'],
                                'bd_id'=>$bdlist['id'],
                                'wid'=>$gslist['wid'],
                                'goods_id'=>$gslist['goods_id'],
                                'goods_sn'=>$gslist['goods_sn'],
                                'goods_name'=>$gslist['goods_name'],
                                'freeze_num'=>$count,
                                'real_num'=>0,
                                'defective_num'=>$gslist['inferior_quality_num']-$count,
                                'operation_userid'=>$this->wprow['uid'],
                                'operation_addtime'=>gmtime(),
                                'batch_no'=>$batch_sn
                            );
                            if($type==2){
                                $bdfrdata['record_type']=3;
                                $bdfrdata['remark']='次品销毁';
                            }elseif ($type==4){
                                $bdfrdata['record_type']=8;
                                $bdfrdata['remark']='次品退货';
                            }
                            //生成次品冻结记录
                            $bdfrid=M('backflow_defectivegoods_freeze_record')->add($bdfrdata);
                            $bddlist=M('backflow_defectivegoods_dispose')->where(array('wid'=>$bdlist['wid'],'batch_sn'=>$batch_sn))->find();
                            if($bddlist){
                                $batch_sn=$bddlist['batch_sn'];
                                $bddbdata=array(
                                    'backflow_dispose_id'=>$bddlist['id'],
                                    'batch_sn'=>$batch_sn,
                                    'bd_id'=>$bdlist['id'],
                                    'wid'=>$bdlist['wid'],
                                    'goods_id'=>$gslist['goods_id'],
                                    'goods_sn'=>$gslist['goods_sn'],
                                    'goods_name'=>$gslist['goods_name'],
                                    'backflow_num'=>$count,
                                    'pending_num'=>$gslist['inferior_quality_num']-$count,
                                    'destroyed_num'=>$count,
                                    'butsales_num'=>0,
                                    'add_time'=>gmtime(),
                                );
                                //生成次品处理批次商品
                                $bddbid=M('backflow_defectivegoods_dispose_batch')->add($bddbdata);
                            }else{
                                $bdddata=array(
                                    'goods_storage_id'=>$bdlist['goods_storage_id'],
                                    'batch_sn'=>$batch_sn,
                                    'wid'=>$bdlist['wid'],
                                    'operation_userid'=>$this->wprow['uid'],
                                    'operation_addtime'=>gmtime(),
                                    'backflow_documents_pic'=>$this->img_site.$path,
                                    'documents_remark'=>$remark,
                                    'status'=>2
                                );
                                //生成次品处理记录
                                $bddid=M('backflow_defectivegoods_dispose')->add($bdddata);
                                if($bddid){
                                    $bddbdata=array(
                                        'backflow_dispose_id'=>$bddid,
                                        'batch_sn'=>$batch_sn,
                                        'bd_id'=>$bdlist['id'],
                                        'wid'=>$bdlist['wid'],
                                        'goods_id'=>$gslist['goods_id'],
                                        'goods_sn'=>$gslist['goods_sn'],
                                        'goods_name'=>$gslist['goods_name'],
                                        'backflow_num'=>$count,
                                        'pending_num'=>$gslist['inferior_quality_num']-$count,
                                        'destroyed_num'=>$count,
                                        'butsales_num'=>0,
                                        'add_time'=>gmtime(),
                                    );
                                    //生成次品处理批次商品
                                    $bddbid=M('backflow_defectivegoods_dispose_batch')->add($bddbdata);
                                }
                            }
                        }
                    }else{
                        $data_return[]=array(
                            'goods_id'=>$gslist['goods_id'],
                            'goods_name'=>$gslist['goods_name'],
                            'goods_num'=>$gslist['goods_sn'],
                            'store_count'=>$gslist['practical_num'],
                            'store_count_bad'=>$gslist['inferior_quality_num'],
                            'err_msg'=>'该商品没有足够的次品',
                        );
                    }
                }else{
                    $data_return[]=array(
                        'goods_id'=>$goods_id,
                        'goods_name'=>'',
                        'goods_num'=>$goods_sn,
                        'store_count'=>0,
                        'store_count_bad'=>0,
                        'err_msg'=>'查无此商品',
                    );
                }
            }elseif ($type==3){//本仓次品回流
                //查看该商品是否在次品冻结库里存在
                $bdlist=$backflow_defectivegoods_mod->where(array('wid'=>$wid,'goods_id'=>$goods_id))->find();
                $gslist=$goods_storage_mod->where(array('wid'=>$wid,'goods_id'=>$goods_id))->find();
                if($bdlist && $gslist){
                    if($count<=0){
                        $data_return[]=array(
                            'goods_id'=>$goods_id,
                            'goods_name'=>$gslist['goods_name'],
                            'goods_num'=>$goods_sn,
                            'store_count'=>$gslist['practical_num'],
                            'store_count_bad'=>$gslist['inferior_quality_num'],
                            'err_msg'=>'该商品操作数请输入大于0的正整数',
                        );
                        continue;
                    }
                    $cache_goods_practical_num=get_goods_practical_num_cache($goods_id, $wid, $gslist['practical_num']);
                    //获取队列库存缓存
                    $cache_queue_goods_stock = get_queue_goods_stock($goods_id, $wid);
                    //次品冻结库存次品数减，同时回流数加
                    if($count>$gslist['inferior_quality_num']){
                        $data_return[]=array(
                            'goods_id'=>$gslist['goods_id'],
                            'goods_name'=>$gslist['goods_name'],
                            'goods_num'=>$gslist['goods_sn'],
                            'store_count'=>$gslist['practical_num'],
                            'store_count_bad'=>$gslist['inferior_quality_num'],
                            'err_msg'=>'该商品没有足够的次品',
                        );
                        continue;
                    }
                    $bdid=$backflow_defectivegoods_mod->where(array('wid'=>$wid,'goods_id'=>$goods_id))->save(array('defectivegoods_num'=>$gslist['inferior_quality_num']-$count,'recycled_num'=>$bdlist['recycled_num']+$count,'operation_addtime'=>gmtime()));
                    $gsid=$goods_storage_mod->where(array('wid'=>$wid,'goods_id'=>$goods_id))->save(array('practical_num'=>$gslist['practical_num']+$count,'inferior_quality_num'=>$gslist['inferior_quality_num']-$count));
                    if($bdid!==false && $gsid!==false){
                        set_goods_practical_num_cache($goods_id, $wid, $cache_goods_practical_num+$count);
                        //更新队列库存缓存
                        set_queue_goods_stock($goods_id, $wid, $cache_queue_goods_stock+$count);
                        $bdfrdata=array(
                            'goods_storage_id'=>$gslist['id'],
                            'bd_id'=>$bdlist['id'],
                            'wid'=>$gslist['wid'],
                            'goods_id'=>$gslist['goods_id'],
                            'goods_sn'=>$gslist['goods_sn'],
                            'goods_name'=>$gslist['goods_name'],
                            'freeze_num'=>$count,
                            'real_num'=>0,
                            'defective_num'=>$gslist['inferior_quality_num']-$count,
                            'operation_userid'=>$this->wprow['uid'],
                            'operation_addtime'=>gmtime(),
                            'batch_no'=>$batch_sn,
                            'record_type'=>4,
                            'remark'=>'重新销售'
                        );
                        //生成次品冻结记录
                        $bdfrid=M('backflow_defectivegoods_freeze_record')->add($bdfrdata);
                        $gsrdata=array(
                            'goods_storage_id'=>$gslist['id'],
                            'wpid'=>0,
                            'goods_id'=>$gslist['goods_id'],
                            'goods_sn'=>$gslist['goods_sn'],
                            'operation_num'=>$count,
                            'real_num'=>$gslist['practical_num']+$count,
                            'frozen_num'=>0,
                            'defective_num'=>0,
                            'operation_userid'=>$this->wprow['uid'],
                            'operation_addtime'=>gmtime(),
                            'source_no'=>$batch_sn,
                            'record_type'=>9,
                            'remark'=>'重新销售'
                        );
                        $gsrid=M('goods_storage_record')->add($gsrdata);
                        if($bdfrid){
                            $bddlist=M('backflow_defectivegoods_dispose')->where(array('wid'=>$bdlist['wid'],'batch_sn'=>$batch_sn))->find();
                            if($bddlist){
                                $batch_sn=$bddlist['batch_sn'];
                                $bddbdata=array(
                                    'backflow_dispose_id'=>$bddlist['id'],
                                    'batch_sn'=>$batch_sn,
                                    'bd_id'=>$bdlist['id'],
                                    'wid'=>$bdlist['wid'],
                                    'goods_id'=>$gslist['goods_id'],
                                    'goods_sn'=>$gslist['goods_sn'],
                                    'goods_name'=>$gslist['goods_name'],
                                    'backflow_num'=>$count,
                                    'pending_num'=>$gslist['inferior_quality_num']-$count,
                                    'destroyed_num'=>0,
                                    'butsales_num'=>$count,
                                    'add_time'=>gmtime(),
                                );
                                //生成次品处理批次商品
                                $bddbid=M('backflow_defectivegoods_dispose_batch')->add($bddbdata);
                            }else{
                                $bdddata=array(
                                    'goods_storage_id'=>$bdlist['goods_storage_id'],
                                    'batch_sn'=>$batch_sn,
                                    'wid'=>$bdlist['wid'],
                                    'operation_userid'=>$this->wprow['uid'],
                                    'operation_addtime'=>gmtime(),
                                    'backflow_documents_pic'=>$this->img_site.$path,
                                    'documents_remark'=>$remark,
                                    'status'=>2
                                );
                                //生成次品处理记录
                                $bddid=M('backflow_defectivegoods_dispose')->add($bdddata);
                                if($bddid){
                                    $bddbdata=array(
                                        'backflow_dispose_id'=>$bddid,
                                        'batch_sn'=>$batch_sn,
                                        'bd_id'=>$bdlist['id'],
                                        'wid'=>$bdlist['wid'],
                                        'goods_id'=>$gslist['goods_id'],
                                        'goods_sn'=>$gslist['goods_sn'],
                                        'goods_name'=>$gslist['goods_name'],
                                        'backflow_num'=>$count,
                                        'pending_num'=>$gslist['inferior_quality_num']-$count,
                                        'destroyed_num'=>0,
                                        'butsales_num'=>$count,
                                        'add_time'=>gmtime(),
                                    );
                                    //生成次品处理批次商品
                                    $bddbid=M('backflow_defectivegoods_dispose_batch')->add($bddbdata);
                                }
                            }
                        }
                    }else{
                        $data_return[]=array(
                            'goods_id'=>$gslist['goods_id'],
                            'goods_name'=>$gslist['goods_name'],
                            'goods_num'=>$gslist['goods_sn'],
                            'store_count'=>$gslist['practical_num'],
                            'store_count_bad'=>$gslist['inferior_quality_num'],
                            'err_msg'=>'该操作次品回流失败',
                        );
                    }
                }else{
                    $data_return[]=array(
                        'goods_id'=>$goods_id,
                        'goods_name'=>'',
                        'goods_num'=>$goods_sn,
                        'store_count'=>0,
                        'store_count_bad'=>0,
                        'err_msg'=>'查无此商品',
                    );
                }
            }
        }
        $data_return_count=count($data_return);
        if($data_return_count>0){
            if($data_return_count ==1){
                returnApiError($data_return[0]['err_msg'],array('data_return'=>$data_return));
            }else{
                returnApiError('部分商品操作成功',array('data_return'=>$data_return));
            }
        }else{
            returnApiSuccess(array('data_return'=>$data_return),'操作成功');
        }

    }

    /*
     *
     * 次品操作记录列表
     * */
    public function bad_handle_log_list(){
        if(!$this->wprow){
            returnApiError("无此操作权限");
        }
        $wid=$this->wprow['wid'];
        $goods_id=I('post.goods_id','intval');
        $page=I('post.page','intval');
        if($goods_id<=0){
            returnApiError('参数错误');
        }
        $where['bdfr.wid']=$wid;
        $where['bdfr.goods_id']=$goods_id;
        $count=M('backflow_defectivegoods_freeze_record')->alias('bdfr')
            ->join(C('DB_PREFIX').'goods_storage as gs on gs.id=bdfr.goods_storage_id')
            ->join(C('DB_PREFIX').'backflow_defectivegoods as bd on bd.id=bdfr.bd_id')
            ->join(C('DB_PREFIX').'goods as g on g.goods_id=bdfr.goods_id')
            ->where($where)
            ->count();
        $pagearr=show_page($count, $page,$this->pagesize);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }
        $list=M('backflow_defectivegoods_freeze_record')->alias('bdfr')
            ->field('bdfr.id,g.goods_id,g.goods_name,g.goods_sn,bd.defectivegoods_num,gs.wid,gs.practical_num,gs.freeze_num,bdfr.freeze_num as operation_num,bdfr.operation_userid,bdfr.operation_addtime,bdfr.batch_no,bdfr.record_type,bdfr.defective_num')
            ->join(C('DB_PREFIX').'goods_storage as gs on gs.id=bdfr.goods_storage_id')
            ->join(C('DB_PREFIX').'backflow_defectivegoods as bd on bd.id=bdfr.bd_id')
            ->join(C('DB_PREFIX').'goods as g on g.goods_id=bdfr.goods_id')
            ->where($where)
            ->order('bdfr.id desc')
            ->limit($pagearr['firstpage'].','.$this->pagesize)
            ->select();
        if($list){
            foreach ($list as $k=>$v){
                $record_type_name='';
                $operation='';
                if($v['record_type']==1){
                    $record_type_name='次品录入';
                    $operation='+';
                }elseif ($v['record_type']==2){
                    $record_type_name='次品回流';
                    $operation='+';
                }elseif ($v['record_type']==3){
                    $record_type_name='次品销毁';
                    $operation='-';
                }elseif ($v['record_type']==4){
                    $record_type_name='重新销售';
                    $operation='-';
                }elseif ($v['record_type']==5){
                    $record_type_name='次品录入';
                    $operation='-';
                }elseif ($v['record_type']==6){
                    $record_type_name='次品回流';
                    $operation='-';
                }elseif ($v['record_type']==7){
                    $record_type_name='次品退款';
                    $operation='+';
                }elseif ($v['record_type']==8){
                    $record_type_name='次品退货';
                    $operation='-';
                }
                $list[$k]['record_type_name']=$record_type_name;
                $list[$k]['operation']=$operation;
                $list[$k]['operation_username']=$this->get_username($v['operation_userid']);
                $list[$k]['operation_addtime']=local_date('Y-m-d H:i:s',$v['operation_addtime']);
                $list[$k]['info']="编号：".$v['id']
                    ."\n来源单号：".$v['batch_no']
                    ."\n商品：".$v['goods_name']." [ ".$v['goods_sn']." ] "
                    ."\n数量：".$v['operation_num']
                    ."\n类型：".$record_type_name
                    ."\n操作：".$operation
                    ."\n次余：".$v['defective_num']
                    ."\n操作员：".$list[$k]['operation_username']." [ ".$list[$k]['operation_addtime']." ] ";
            }
            returnApiSuccess(array('list'=>$list,'is_last'=>$is_last),'success');
        }else{
            returnApiSuccess(array('list'=>array(),'is_last'=>1),'没有数据');
        }
    }

    /**
     * 查看商品是否可操作
     *
     */
    public function check_goods_num(){
        if(!$this->wprow){
            returnApiError("无此操作权限");
        }
        $wid=$this->wprow['wid'];
        $goods_sn=I('post.goods_num');
        $type=I('post.type','intval');
        if(empty($goods_sn) || in_array($type, array(1,2,3))===false){
            returnApiError('参数错误');
        }
        if($type==1){
            $where['gs.wid']=$wid;
            $where['g.goods_sn']=$goods_sn;
            $where['g.is_delete']=0;
            $count=M('goods_storage')->alias('gs')
                ->join(C('DB_PREFIX').'goods as g on g.goods_id=gs.goods_id')
                ->where($where)
                ->count();
            if($count>0){
                returnApiSuccess(array('goods_num'=>$goods_sn),'success');
            }else{
                returnApiError('查无此商品');
            }
        }elseif($type==2 || $type==3){
            $where['bd.wid']=$wid;
            $where['g.goods_sn']=$goods_sn;
            $where['g.is_delete']=0;
            $backflow_defectivegoods_mod=M('backflow_defectivegoods');
            $count=$backflow_defectivegoods_mod->alias('bd')
                ->join(C('DB_PREFIX').'goods_storage as gs on gs.id=bd.goods_storage_id')
                ->join(C('DB_PREFIX').'goods as g on g.goods_id=bd.goods_id')
                ->where($where)
                ->count();
            if($count>0){
                returnApiSuccess(array('goods_num'=>$goods_sn),'success');
            }else{
                returnApiError('查无此商品');
            }
        }
    }
    /*
     * 对象转数组
     * */
    private function objarray_to_array($obj) {
        $ret = array();
        foreach ($obj as $key => $value) {
            if (gettype($value) == "array" || gettype($value) == "object"){
                $ret[$key] =  $this->objarray_to_array($value);
            }else{
                $ret[$key] = $value;
            }
        }
        return $ret;
    }

    /**
     * 盘点正常 【读取上一次盘点的内容 在进行写入一次】
     */
    public function check_ok(){
        returnApiError("此功能暂停使用");
        $user_id=I('post.user_id');    //用户ID
        $good_id=I('post.good_id');    //商品ID
        $remark=I('post.remark');               //备注
        if(empty($good_id)){
            returnApiError("商品ID为空");
        }else {
            //查询此商品的缓存记录--只查询缓存中，未上传的记录
//            $goods_data = M("goods")->where(array("goods_id" => $good_id))->field("goods_sn,goods_name")->find();
//
//            $shelves_goods = M("shelves_goods")->
//            where(array("goods_sn" => $goods_data['goods_sn']))->select();
            $new_number = 10;
//            $str = array();
//            foreach ($shelves_goods as $key => $value) {
//                $cache_data = M("take_stock_inventory_cache")->
//                where(array("goods_id" => $good_id, "type" => 1, "sh_id" => $value['sh_id'], "line" => $value['sh_floor']))->order("ctime desc")->find();
//                if (!$cache_data) {
//                    returnApiError("有货架记录未盘点过");
//                }
//                $new_number = $new_number + $cache_data['now_number'];
//                $str[] = $cache_data['id'];
//            }
//            dump($new_number);
//            exit();
            if ($new_number >= 0) {
                $re = $this->set_check_count($user_id, $good_id, $new_number, $remark, 1, $shelf = false);
                //returnApiError($new_number);
                if ($re['state']) {
//                    foreach ($str as $value2) {
//                        $cache_data = M("take_stock_inventory_cache")->
//                        where(array("id" => $value2))->order("ctime desc")->find();
//                        $data['ctime'] = gmtime();
//                        $data['sh_id'] = $cache_data['sh_id'];
//                        $data['goods_name'] = $cache_data['goods_name'];
//                        $data['goods_sn'] = $cache_data['goods_sn'];
//                        $data['type'] = 1;
//                        $data['now_number'] = $cache_data['now_number'];
//                        $user_info = A("Distribution")->get_admin_user_name($user_id);
//                        $data['user'] = $user_info['user_name'];
//                        $data['remark'] = $remark;
//                        $data['goods_id'] = $cache_data['goods_id'];
//                        $data['line'] = $cache_data['line'];
//                        $data['show'] = 0;
//                        M("take_stock_inventory_cache")->add($data);
//                    }

                    returnApiSuccess(null, "成功");
                } else {
                    returnApiError($re['msg']);
                }
            } else {
                returnApiError("缓存数据已经被提交，请重新打开");
            }

        }
    }

    /**
     * 货架筛选 新
     */
    public function shelf_get_select(){
        $user_id = I("post.user_id");
        $user_wid = $this->get_user_wid_identity($user_id);
        $shelves_cat = M("shelves_cat")->select();
        foreach ($shelves_cat as $key=>$value){
            $shelves_cat[$key]['count'] = M("shelves")->where(array("category_id"=>$value['id'],"wid"=>$user_wid))->count();
        }
        $shelves_class = M("shelves_class")->select();
        foreach ($shelves_class as $key=>$value){
            $shelves_class[$key]['count'] = M("shelves")->where(array("class_id"=>$value['id'],"wid"=>$user_wid))->count();
        }

        $all_array = array(
            "name" =>"全部",
            "id" =>"0",
            "tag" =>"ALL",
            "count"=>M("shelves")->where(array("wid"=>$user_wid))->count()
        );

        array_push($shelves_cat,$all_array);

        array_push($shelves_class,$all_array);

        $data['list_tag'] = $shelves_cat;
        $data['list_type'] = $shelves_class;
        returnApiSuccess($data,"数据已返回");
    }

    /**
     * 新版货架列表
     */
    public function shelf_list_02(){
        $user_id=I('post.user_id','intval');            //用户ID
        $page=I('post.page','intval');                  //页数
        $shelf_tag=I('post.shelf_tag','intval');        //货架标签【食品区】
        $shelf_type=I('post.shelf_type','intval');      //货架类型【端架】
        $list_type=I('post.list_type','intval');        //显示类型 0全部，1屏蔽无货，2屏蔽已盘，3屏蔽停用
        $start_data = I('post.start_date');
        $end_data = I('post.end_date');
        if(empty($page)){
            $page =1 ;
        }
        $start_num = ($page-1)*20;
        $wid = $this->get_user_wid_identity($user_id);


        if($list_type==2){
            //筛选已盘
            $limit = "";

//            $start_data = "2017-03-18";
//            $end_data = "2017-04-18";
            if(empty($start_data)&&empty($end_data)){
                returnApiError("开始时间/结束时间为空");
            }
        }else{
            $limit =   "LIMIT $start_num,20";
        }

        if(empty($start_data)&&empty($end_data)){
            $input_data = false;
        }else{
            $input_data = true;
        }

        $where ="";
        if($list_type==3){
            //屏蔽禁用
            $where .="  AND sh.state = 1";
        }
        if(!empty($shelf_tag)){
            $where.=" AND sh.category_id = '$shelf_tag'";
        }
        if(!empty($shelf_type)){
            $where.=" AND sh.class_id = '$shelf_type'";
        }
        if($list_type==1){
            //屏蔽无货
            $where .="  AND sh.id IN (SELECT distinct(sh_id) FROM sdx_shelves_goods)";
        }



        $model = M();
        $sql = "SELECT sh.id AS shelf_id,sc.name AS shelf_tag,sl.name AS shelf_type,wh.name AS shelf_store,sh.state AS shelf_state,
                sh.shelves_sn AS shelf_num,sh.s_floor AS shelf_row,sh.wid AS shelf_store_id,
                sh.category_id AS shelf_tag_id,sh.class_id AS shelf_type_id,sh.sort
                FROM sdx_shelves AS sh,sdx_shelves_cat AS sc,sdx_shelves_class AS sl ,sdx_warehouse AS wh WHERE 
                sh.category_id = sc.id AND sh.class_id = sl.id $where
                AND sh.wid =  wh.id AND sh.wid = ".$wid." ORDER BY sh.sort ASC $limit";
        //dump($sql);
        $list = $model->query($sql);

        if($list){
            foreach ($list as $key=>$value){
                //此货架一共存放商品种类数
                $sql_num ="SELECT COUNT(*) AS num FROM  (SELECT count(*) FROM sdx_goods AS g ,sdx_shelves_goods AS sg WHERE g.goods_sn = sg.goods_sn AND sg.sh_id= ".$value['shelf_id']." GROUP BY sg.goods_sn) u";
                $list_num = $model->query($sql_num);
                $list[$key]['count_goods_type'] = $list_num[0]['num'];

                $i = 0;
                if($list_num[0]['num']>0){
                    //此货架今日未盘点商品种类数//此货架所有商品
                    $goods_list = M("shelves_goods")->where(array("sh_id"=>$value['shelf_id']))->group("goods_sn")->getField("goods_sn",true);


                    foreach ($goods_list as $key2=>$value2){
                        if(M("goods")->where(array("goods_sn"=>$value2))->count()){
                            $line_array = M("shelves_goods")->where(array("sh_id"=>$value['shelf_id'],"goods_sn"=>$value2))->getField("sh_floor",true);
                            foreach ($line_array as $value3){
                                if($input_data){
                                    //筛选已盘
                                    $where_cahe = "line = ".$value3." AND (TO_DAYS(from_unixtime(ctime+28800)) BETWEEN  TO_DAYS('".$start_data."')  AND TO_DAYS('".$end_data."')) AND sh_id = '".$value['shelf_id']."' AND type = 1 AND goods_sn = '".$value2."'";
                                }else{
                                    $where_cahe = "line = ".$value3." AND TO_DAYS(from_unixtime(ctime+28800)) = TO_DAYS(now()) AND sh_id = '".$value['shelf_id']."' AND type = 1 AND goods_sn = '".$value2."'";
                                }
                                $is_pd = M("take_stock_inventory_cache")->where($where_cahe)->count();
                                //dump(M("take_stock_inventory_cache")->getLastSql());
                                if($is_pd==0){
                                    $i++;
                                }
                            }
                        }
                    }
                }
                $list[$key]['count_no_check_goods'] = $i;

                if($list[$key]['count_no_check_goods']==0&&$list_type==2){
                    unset($list[$key]);
                }
            }
            $data['data'] = array_values($list);
            if(count($list)<20){
                $data['is_last'] = 1;
            }else{
                $data['is_last'] = 0;
            }
            if($list_type==2){
                //屏蔽已盘
                $data['is_last'] = 1;
            }
            returnApiSuccess($data,"数据已返回");
        } else {
            returnApiError("未获取到数据");
        }
    }

    /**
     *缺货退款商品记录列表
     */
    public function goods_lack_list(){
        $page=I("post.page");
        if(empty($page)){
            $page = 1;
        }
        $start_num = ($page-1) *10;

        $model = M();
        $sql = "SELECT rl.log_id,rl.order_id,rl.order_sn,rl.admin_user,(rl.refund_time + 28800) AS refund_time ,rl.admin_note,rd.goods_id,rd.goods_name,rd.goods_sn,rd.refund_number
FROM sdx_refund_log AS rl,sdx_refund_detail AS rd WHERE rl.refund_type='缺货退款' AND rl.log_id= rd.log_id ORDER BY rl.log_id DESC LIMIT {$start_num}, 10";
        //dump($sql);
        $list = $model->query($sql);

        if($list){
            $data['list'] = $list;
            if(count($list)<10){
                $data['is_last'] = 0;
            }else{
                $data['is_last'] = 1;
            }
        }else{
            $data['is_last'] = 1;
        }
        returnApiSuccess($data,'已返回');
    }
}